2

Below is the code :

var a ="10.9549999999999141";
console.log(a);
console.log(typeof a);
console.log(Number(a));

Now the above code results as below :

"10.9549999999999141"
"string"
10.954999999999915

Here See the value got rounded off from 10.9549999999999141 to 10.954999999999915, as the result of query comes in string so i want to convert the exact same value to number avoiding round off.

Can any one help ?

Jignesh Mistry
  • 2,221
  • 6
  • 25
  • 50
  • 4
    Relevant: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Amadan Sep 17 '19 at 09:40
  • Yes it seems to be – Jignesh Mistry Sep 17 '19 at 09:41
  • 1
    Javascript itself can only handle up to 16 digits. If you want to be more precise, then you would need to use a specialized library. [This answer](https://stackoverflow.com/a/21278297/9038475) should be helpful for you. – Geshode Sep 17 '19 at 09:42
  • 1
    probably duplicate, check here: https://stackoverflow.com/questions/4640404/parsefloat-rounding – EigenFool Sep 17 '19 at 09:42
  • 1
    You maybe could try to convert to [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). But then you need to keep track of the used exponent on your own. – Sirko Sep 17 '19 at 09:43
  • 1
    There's [libraries](https://github.com/MikeMcl/decimal.js/) for this, though, using fixed-point arithmetic. `Decimal("10.9549999999999141")` will be precise. – Amadan Sep 17 '19 at 09:48

1 Answers1

-2

Sorry If I answer your question wrongly, but my answer is parseFloat(); Maybe you can hava a try!!!

  • Have you tried it? `parseFloat` exhibits the same behaviour as `Number`, in this case (having nothing to do with the function itself, but with the inadequacy of the float datatype). – Amadan Sep 17 '19 at 09:51
  • pls use snipet to confirm your answer – Deepak A Sep 17 '19 at 09:58