Skip to content Skip to sidebar Skip to footer

Rounding A Number To One Decimal In Javascript

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.

Solution 1:

Use toFixed:

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

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

Solution 2:

Math.round(total * 10) / 10

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

Solution 3:

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

functioncomputeTotalDistance(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

Solution 4:

There is a function to do what you want:

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

It will be printed 41.76

Post a Comment for "Rounding A Number To One Decimal In Javascript"