12

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;
});
Muhammad ADIL
  • 303
  • 2
  • 10
  • 1
    check it again http://jsfiddle.net/XegE3/5/ – Rakesh Kumar Feb 11 '14 at 05:06
  • It might display extra "random" numbers at the end, but it *will* be "1212.x" for the integer part if the number is originally "12.x". Did you incorrectly copy the output? – user2864740 Feb 11 '14 at 05:11
  • it has nth to do with jquery, its due to javascript floating numerical representation. – zuo Feb 11 '14 at 05:11
  • Also you maybe want to look up this question: [JS floating number problem](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem) – nes Feb 11 '14 at 05:18

4 Answers4

6

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

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

nes
  • 1,046
  • 1
  • 7
  • 10
2

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

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

bb94
  • 1,294
  • 1
  • 11
  • 24