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?
source to share
Use toFixed
:
var total = 41.76483039399999;
total = total.toFixed(1) // 41.8
Here's a fiddle: http://jsfiddle.net/VsLp6/
source to share
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
source to share