Steven Steven - 3 months ago 8
Javascript Question

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?

Answer

How about this:

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

or:

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

to show it as an actual dollar amount.