Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong value after multiplication by 100 [duplicate]

Tags:

javascript

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;
});
like image 568
Muhammad ADIL Avatar asked Feb 11 '14 05:02

Muhammad ADIL


4 Answers

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.

like image 159
Ja͢ck Avatar answered Sep 23 '22 16:09

Ja͢ck


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

like image 23
nes Avatar answered Sep 21 '22 16:09

nes


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.

like image 22
Bhojendra Rauniyar Avatar answered Sep 23 '22 16:09

Bhojendra Rauniyar


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).

like image 21
bb94 Avatar answered Sep 22 '22 16:09

bb94