In my code, I have this:

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

If, for example,the input is: 123.12 + 12.22, the Balance is 135.34 But if the input is : 123.00 + 12.00, the Balance is 135 instead of 135.00.

What should I add to achieve the 2nd output sample?

Thanks.

有帮助吗?

解决方案

Use ToFixed(2) mdn

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

Also , use || operator.

So :

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);
}

Small gotcha :

(9.999 +9.999).toFixed(2) //"20.00"

So how would I solve it ? 

simply :

Multiply by 1000 each and then move decimal point.

其他提示

It sounds like parseFloat() is working correctly but it's the output that isn't quite to your liking. Try using Number's .toFixed() function for formatting:

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

There's some great discussions of formatting currency over on this question: How can I format numbers as money in JavaScript?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top