Question

I'm doing a simple subtraction with Javascript and the result doesn't match with the real result:

<html>
<head>
    <title></title>
</head>
<body>

<table>
<tr><td>Price: </td><td><input type="text" id="price" value="4500.60" onblur="calculatePrecio();"></td></tr>
<tr><td>Discount: </td><td><input type="text" id="discount" value="500" onblur="calculatePrecio();"></td></tr>
</table>

<div id="divTotalAmount"></div>

<script>

calculatePrecio();

function calculatePrecio()
{
    var price = document.getElementById('price').value;
    var discount = document.getElementById('discount').value;

    p = price;
    d = discount;

    totalAmount = p - d;

    document.getElementById('divTotalAmount').innerHTML = "<h1>"+totalAmount+"</h1>";
}

</script>

</body>
</html>

Can you guys help me? In addition I just don't want to know how to proceed, I want to know the reason for this, if possible.

Était-ce utile?

La solution

To format the output you can simply used the toFixed method.

var x = 5.3, y = 3;
var z = (x - y).toFixed(2);

HERE is the working jsFiddle.

Autres conseils

you can use totalAmount.toFixed(2) for example .... it will be somthing like this xxxxxxxx.xx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top