Rounding a number to one decimal in javascript [duplicate]

可紊 提交于 2020-03-22 03:40:16

问题


Possible Duplicate:
How do you round to 1 decimal place in 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 total to one decimal place?


回答1:


Use toFixed:

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

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




回答2:


Math.round(total * 10) / 10

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




回答3:


You are looking for Number.prototype.toFixed; 41.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 Math or instances of Number

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



回答4:


There is a function to do what you want:

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

It will be printed 41.76



来源:https://stackoverflow.com/questions/14461017/rounding-a-number-to-one-decimal-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!