ParseFloat混乱

时间:2014-03-03 05:39:40

标签: javascript decimal

在我的代码中,我有这个:

<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。

我应该添加什么才能获得第二个输出样本?

感谢。

2 个答案:

答案 0 :(得分:3)

使用ToFixed(2) mdn

(123.00 + 12.00).toFixed(2) //135.00

另外,使用||操作

所以:

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,然后移动小数点。

答案 1 :(得分:1)

听起来parseFloat()工作正常,但输出并不是您喜欢的。尝试使用Number's .toFixed()函数进行格式化:

Balance.value = (collect + current).toFixed(2)

在这个问题上有关于格式化货币的一些很好的讨论:How can I format numbers as money in JavaScript?