The jQuery displays 12.123456789123003 instead of 12.123456789123 when this value 1212.3456789123 multiplies with 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;
});
Because of the non-exact nature of floating point values (this is not JavaScript's fault), 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 fraction.
JavaScript has problems with floating point numbers precision.
If you want precise results in JS, like when you working with money, you need use something like BigDecimal
There is 12 digits in decimal portion so when 12.123456789123 is multiplied by 100 1212.3456789123
doesn't contain the 12 digits so it's filling remaining numbers that's it.
This is a rounding error. Don't use floating-point types for currency values; you're better off having the price be in terms of the smallest integral unit. It's quite unusual to have prices be in precise units like that. If you really need to use a floating-point type, then use 1e-12 * Math.round(1e14 * v)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With