0

If I try to convert below value to Number or parseFloat, the decimal precision getting lose.

var tt = "1234.12345678912345"

console.log(tt);

var ss = Number(tt);
console.log(ss);

var rr = parseFloat(tt);
console.log(rr);

var ee = +(tt);
console.log(ee);

var ww = tt * 1;
console.log(ww);

Please check the code snippet. enter image description here Is there a way to convert a string to Number without losing decimal precision?

Cegone
  • 489
  • 1
  • 9
  • 23
  • 2
    Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – evolutionxbox Jan 07 '21 at 13:51
  • Probably not. What are you trying to do? (do arithmetic operations on them?) – user202729 Jan 07 '21 at 13:51
  • 1
    There's [floating point - How to deal with big numbers in javascript - Stack Overflow](https://stackoverflow.com/questions/4288821/how-to-deal-with-big-numbers-in-javascript) but you'd better finding a library yourself than relying on answers there. – user202729 Jan 07 '21 at 13:53
  • @user202729 - we need to pass this user entered value to db. – Cegone Jan 07 '21 at 13:56
  • 2
    Then pass it as a string. – Felix Kling Jan 07 '21 at 13:56
  • In our scenario, we can't, we need to pass the value as a number type – Cegone Jan 07 '21 at 13:58
  • To avoid XY problems, it's better to explain clearly why you need those requirements, what database program you're using, etc. – user202729 Jan 07 '21 at 14:01
  • 3
    JavaScript, like almost all other modern languages on almost all common computing platforms, uses IEEE 754 floating point. It's how the actual hardware represents the numbers. The "problem" is not with JavaScript; you would encounter the same problems in C or C++ or Java. You could *possibly* use some sort of "big decimal" package, if that works for the sort of computations you do. JavaScript does not have such a facility as part of the standard runtime, but there are solutions out there. – Pointy Jan 07 '21 at 14:01
  • 2
    Note also that if the "user entered value" is coming from a web page, it's going to be passed to your server as a string anyway. You can defer the numeric conversion to that environment, which may give you other options. – Pointy Jan 07 '21 at 14:03
  • @Pointy - Thank you, I'll consider your suggestion. – Cegone Jan 07 '21 at 14:16

0 Answers0