在我的代码中,我有这个:
<script language="javascript">
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value);
var current = parseFloat(document.getElementById("Current").value);
var Balance = document.getElementById("Bal");
Balance.value = collect + current;
}
</script>
例如,如果输入为:123.12 + 12.22,则余额为 135.34
但是如果输入是:123.00 + 12.00,余额是 135 而不是 135.00。
我应该添加什么来实现第二个输出示例?
谢谢。
最佳答案
使用 ToFixed(2)
mdn(123.00 + 12.00).toFixed(2)
//135.00
另外,使用 ||运算符(operator)。
所以 :
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value) ||0;
var current = parseFloat(document.getElementById("Current").value) ||0;
var Balance = document.getElementById("Bal");
Balance.value = (collect + current).toFixed(2);
}
小问题:
(9.999 +9.999).toFixed(2)
//"20.00"So how would I solve it ?
简单地 :
每个乘以 1000,然后移动小数点。
关于javascript - ParseFloat 混淆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22139433/