문제

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