Home > Mobile >  parseFloat stripping last digits and converting to zeros
parseFloat stripping last digits and converting to zeros

Time:06-17

I have a scenario where I need to parsefloat 19 digit string to number. e.g. parseFloat("1000000000100000043") gives me 1000000000100000000 but the expected output required is 1000000000100000043

CodePudding user response:

You are running into how Javascript numbers are stored. See, e.g., here: https://www.w3schools.com/js/js_numbers.asp

You can use a library like decimal.js to work with large, exact numbers. These libraries store the number as string, but allow you to do mathematical operations.

CodePudding user response:

This is likely a precision overflow error.

The Number data type (but also int and float in other languages) have a finite number of bits available to represent a number. Typically around 15-16 decimal digits worth.

When length of original number in the string exceeds available precision, such number can no longer be represented by the target data type.

In this case the parseFloat function fails silently. If you want to catch this situation you need to add code to check incoming data or use another function, possibly a custom one. Alternatively, you can convert the numeric value back to string and compare it with original to detect a discrepancy.

See also a question regarding double.Parse

  • Related