Invalid value after multiplying by 100

jQuery displays 12.123456789123003 instead of 12.123456789123 when this value of 1212.3456789123 is multiplied by 100.

code:

<p class="price">12.123456789123</p> <button>Calculate</button> $(':button').click(function () { $('p.price').text(function (i, v) { return v * 100; }); this.disabled = true; }); 
+6
source share
4 answers

Due to the inaccurate nature of the floating point values ​​(this is not a JavaScript error) you need to be more specific, i.e.:

 $('p.price').text(function (i, v) { return (v * 100).toFixed(10); }); 

Where .toFixed(10) determines the desired size of your share.

+3
source

JavaScript has problems with the precision of floating point numbers.

If you need accurate results in JS, for example, when you work with money, you need to use something like BigDecimal

+2
source

There are 12 digits in the decimal part, so when 12.123456789123 is multiplied by 100 1212.3456789123 does not contain 12 digits, so it fills the remaining numbers.

+2
source

This is a rounding error. Do not use floating point types for currency values; you better have a price in terms of the smallest integral unit. It is rather unusual for prices to be in exact units. If you really need to use a floating point type, use 1e-12 * Math.round(1e14 * v) .

+1
source

All Articles