Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number to one decimal in javascript [duplicate]

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?

like image 212
Robert Martens Avatar asked Nov 28 '22 07:11

Robert Martens


1 Answers

Use toFixed:

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

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

like image 98
Joseph Silber Avatar answered Dec 09 '22 18:12

Joseph Silber