Float *. 100 rounding issue

Hey everyone, looking to convert a string from an input ie. "19.99" and get this to an Int 1999 but when we do our basic multiplication by 100 to accomplish this we get 1998.9999999999998 and then when this gets casted to an Int we will get 1998.

Here is the code:

(localAmount->Belt.Float.fromString->Belt.Option.getWithDefault(0.0) *. 100.0)->Belt.Float.toInt //1998.9999999999998 

Thanks in advance!

1 Like

I assume your question is ‘Why is this happening and how can I prevent it?’ :slightly_smiling_face:

This is the classic binary floating point representation issue and it’s not happening because of ReScript, it’s common to many languages and platforms, including JavaScript: https://0.30000000000000004.com/

The correct way to handle this would be to use a decimal floating point library like bigdecimal - npm . A hacky way to handle it would be to realize that the string "19.99" can be manipulated a little bit to turn it into "1999", and then use Belt.Int.fromString on that to get 1999.

3 Likes

I would at some point try to use .toFixed method (I guess Js.Float.toFixed)

image

3 Likes

Thanks everyone, yes @yawaramin - I had a feeling this was not a rescript specific floating point issue, just was not sure how to best solve the issue with rescript.

Thanks so much for both the suggestions, I ended up going with the Js.Float.toFixed - worked perfectly.