javascript 在javascript中将数字四舍五入为一位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14461017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:40:54  来源:igfitidea点击:

Rounding a number to one decimal in javascript

javascriptmathgoogle-maps-api-3

提问by Robert Martens

Possible Duplicate:
How do you round to 1 decimal place in Javascript?

可能的重复:
如何在 Javascript 中四舍五入到小数点后一位?

The following code, displays the total distance covered, on a particular route, displayed on google maps. I managed to convert the number from kilometers to miles. Here is the code for the function:

以下代码显示在特定路线上覆盖的总距离,显示在谷歌地图上。我设法将数字从公里转换为英里。下面是该函数的代码:

function computeTotalDistance(result) {
        var total = 0;
        var myroute = result.routes[0];
        for (i = 0; i < myroute.legs.length; i++) {
          total += myroute.legs[i].distance.value;
        }
        total = total *0.621371/ 1000.
        document.getElementById('total').innerHTML = total + ' mi';

The total is displayed as 41.76483039399999 mi. How would round off the totalto one decimal place?

总数显示为41.76483039399999 mi。如何将四舍五入total到小数点后一位?

回答by Joseph Silber

Use toFixed:

使用toFixed

var total = 41.76483039399999;
total = total.toFixed(1) // 41.8

Here's the fiddle: http://jsfiddle.net/VsLp6/

这是小提琴:http: //jsfiddle.net/VsLp6/

回答by PinkElephantsOnParade

Math.round(total * 10) / 10

This results in a number. toFixed() gives a string, as detailed in other answers.

这导致了一个数字。toFixed() 给出一个字符串,如其他答案中所述。

回答by Paul S.

You are looking for Number.prototype.toFixed; 41.76483039399999.toFixed(1) === "41.8";

您正在寻找Number.prototype.toFixed41.76483039399999.toFixed(1) === "41.8";

function computeTotalDistance(result) {
    var total = 0, myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
    }
    total = (total * 0.621371 / 1000).toFixed(1);
    document.getElementById('total').innerHTML = total + ' mi';
}

There are a very many other ways to achieve this, for example, without using any methods from Mathor instances of Number

有很多其他方法可以实现这一点,例如,不使用任何方法Math或实例Number

(~~(10 * total) + (~~(100 * total) % 10 >= 5))/10 + '' // "41.8"
// (      417   +     (6 >= 5)               )/10 = 41.8

回答by igarcia

There is a function to do what you want:

有一个功能可以做你想做的事:

var total = 41.76483039399999; print(x.toFixed(2));

无功总计 = 41.76483039399999;打印(x.toFixed(2));

It will be printed 41.76

它将打印 41.76