如何将总数修复为2位小数html / javascript

问题描述 投票:2回答:3

我有以下javascript代码在选中时添加复选框并生成总计。我需要添加什么来使代码总是显示2位小数。

<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) { 
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
</script>
javascript html currency decimal running-total
3个回答
2
投票

你只需要调用toFixed(n)并传递小数点后的位数:

document.listForm.total.value = sum.toFixed(2);

0
投票

你可以使用toFixed()方法:http://www.w3schools.com/jsref/jsref_tofixed.asp


0
投票

只需创建一个功能:

  function fixedPlace(x) {
    return Number.parseFloat(x).toFixed(2);
  }

并调用此函数,如:

var output = fixedPlace(3.1416);

它将返回3.14

© www.soinside.com 2019 - 2024. All rights reserved.