Search code examples
javascriptparsefloattofixed

Javascript unexpected parsefloat behavior?


I am aware this question has been asked before and i have read up on the subject, but still the solution isn't clear to me. And my attempts fails.

<div class="subtotal" data-content="€">30.50</div>

but with the following jquery js it reads 30.509

test = parseFloat($('.subtotal').text());//reads 30.509

i tried

test = parseFloat(Number($('.subtotal').text()).toFixed(2));//gives NaN

How do i make sure javascript reads the subtotal as 30.50 and not 30.509?

Regards,


Solution

  • It doesn't read a different value. The difference comes because of the precision of how the floating point numbers are stored in memory. As you store a number, you don't need to worry about that. You'll never be able to store it exactly as you want.

    When displaying the number you'll have to trim it to two decimals, which should correctly display it as it was read. Your problem is just about how the number is displayed.