在javascript中将数字四舍五入到小数点后一位 [英] Rounding a number to one decimal in javascript
本文介绍了在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. 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';
总计显示为41.76483039399999 mi
.如何将total
舍入到小数点后一位?
The total is displayed as 41.76483039399999 mi
. How would round off the total
to one decimal place?
推荐答案
使用 toFixed
:
var total = 41.76483039399999;
total = total.toFixed(1) // 41.8
这是小提琴: http://jsfiddle.net/VsLp6/
这篇关于在javascript中将数字四舍五入到小数点后一位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文