Search code examples
javascriptjqueryfloating-accuracy

The Jquery displays $20.099999999999998 instead of $20.1


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?


Solution

  • How about this:

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

    or:

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

    to show it as an actual dollar amount.