1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    Perhaps you're wondering: [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – apsillers Apr 04 '13 at 14:24
  • 1
    Read about floating point arithmetic: http://floating-point-gui.de/ – C. Reed Apr 04 '13 at 14:26
  • 1
    You can use `.toFixed()`, as the answers suggest, but it's always somewhat perilous to do "money math" with a floating point numeric system. – Pointy Apr 04 '13 at 14:26

2 Answers2

4

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.

flavian
  • 28,161
  • 11
  • 65
  • 105
  • Thank you for all the anwsers. It's so strange this about "double precision" but I love learning and I'm very interested on this! Thanks! – user1912771 Apr 05 '13 at 06:52
1

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

arnoldrob
  • 813
  • 3
  • 9
  • 15