views:

147

answers:

4

This is the Jquery code:

  function Totalprice()
{
    var unitprice=$('#unitpay').val();
    var quota=$('#readers').val();
    var totalprice=unitprice*quota;
    $('#totalprice').text('$'+totalprice);

}

When the value of readers is 67 and the unitpay is 0.3, it calculates the total price and displays $20.099999999999998 , not $20.1. What's wrong? If I want it to display $20.1 instead of $20.099999999999998, how can I rewrite the code?

+6  A: 

How about this:

$('#totalprice').text('$'+totalprice.toFixed(1));

or:

$('#totalprice').text('$'+totalprice.toFixed(2));

to show it as an actual dollar amount.

Swingley
great! great! Great!
Steven
+2  A: 

Just use .toFixed(2). (link)

The problem is that computers can't exactly represent some numbers (they're finite, and operate in binary), so stuff like this happens.

Mark
+5  A: 

As your enthusiastic commentators pointed out, it's a floating point error. The quick and easy solution is to use a rounding method like toFixed().

keithjgrant
A: 

Javascript has some pretty severe floating point issues. Try typing 0.1+0.2 in your Firebug console sometime for some fun.

This isn't an issue with jQuery. As has been mentioned above, use toFixed().

Scottie