Home > OS >  Parse Float string to number rounding off javascript
Parse Float string to number rounding off javascript

Time:06-03

I have the string "9999999999999.99999" which I covert using Parse Float. But it changes the value to 10000000000000 , is there anyway I can have the get the number same without rounding off?

The input is string and out must be number not string. ex: ParseFloat("9999999999999.99999") = 9999999999999.99999 . So the output should not be string instead number

CodePudding user response:

Well there is a bit limit to what numbers Javascript can handle (until we get BigInt64 or if you use a library like decimal.js). So since it cannot handle more decimals it just truncates at a point. If you would make a bigger number you would see less decimals. If this then leads to the number being "exacly" 9999999999999.99 in your case javascript will correctly show it as 9999999999999.99 and not 9999999999999.99999 since we only have Number and not float, decimal, int, etc.

parseFloat(9999999999999.99999);
// 9999999999999.99
parseFloat(9999999999999.9999);
// 9999999999999.99
parseFloat(9999999999999.999);
// 9999999999999.998
parseFloat(9999999999999.99);
// 9999999999999.99

Edit: actually it seem to round and not drop.

I hope that explains things.

CodePudding user response:

You could have a look at decimal.js, this allows an arbitrary level of precision to be specified.

const x = new Decimal("9999999999999.99999");
console.log('x:', x.toString())

// Manipulate x
console.log('x * 2:', x.mul(2).toString())
console.log('x / 2:', x.div(2).toString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js" integrity="sha512-zPQm8HS4Phjo9pUbbk HPH3rSWu5H03NFvBpPf6D9EU2xasj0ZxhYAc/lvv/HVDWMSE1Autj19i6nZOfiVQbFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related