Rounding a number to one decimal place in javascript

Possible duplicate:
How do you get around to 1 decimal place in Javascript?

The following code displays the total distance traveled for a specific route displayed on google maps. I managed to count 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 you round total

to one decimal place?

+3


source to share


4 answers


Use toFixed

:

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

      



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

+10


source


Math.round(total * 10) / 10

      



The result is a number. toFixed () gives a string as described in other answers.

+11


source


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 many other ways to achieve this, for example without using any methods from Math

or instancesNumber

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

      

+1


source


There is a function to do what you want:

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

It will print 41.76

0


source







All Articles