0

I am working on a finance application where a small decimal point matters a lot. While I was working at it, I discovered that js changes the actual value when transforming to to hex and decimal to and fro.

For example:

a = (parseFloat(49098.40463663199) * 10 **18).toString(16)

gives me

a65a13dc28529800000

Adding 0x at the beginning and dividing by the number it was multiplied to changes the number slightly like:

0xa65a13dc28529800000 / 10 ** 18

gives me

49098.40463663198

Notice that the value decreased by 0.00000000001?

I want to avoid this. How can I?

Here is the picture for the same calculation on console: Console picture

dexter
  • 27
  • 5
  • Working with floats in `javascript` comes along with some known problems.. This may help? . https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Silvan Bregy Feb 14 '22 at 10:50
  • 1
    You're exceeding the precision that the IEEE-754 double-precision floating point number type used by JavaScript can maintain, which is roughly 15 decimal digits of precision (roughly because the limit is binary, not decimal, but it's between 15 and 16 digits). Separately, `parseFloat(49098.40463663199)` makes no sense, `49098.40463663199` is *already* a number. `parseFloat` is for parsing *strings* into numbers. – T.J. Crowder Feb 14 '22 at 10:51
  • 3
    *"I am working on a finance application where a small decimal point matters a lot."* Then you can't use JavaScript's `number` type for it. (Some day you'll be able to use [Decimal](https://github.com/tc39/proposal-decimal), but not yet.) There are various libraries you can use, or you can use a `BigInt` holding the values as whole numbers (expressed hundredths or thousandths or ten-thousandths of the base currency). – T.J. Crowder Feb 14 '22 at 11:17
  • 1
    FWIW, you can get a floating point hex string from a number directly: `(49098.40463663199).toString(16)` is `"bfca.6796442d28"`. If you want a non-fractional one representing the IEEE-754 binary64 bits that make up the number, you can get that [like this](https://jsfiddle.net/tjcrowder/1k03wpmd/). But again, if you're doing a financial app, the number type isn't the type to use. – T.J. Crowder Feb 14 '22 at 11:29

0 Answers0