phillip-le / phillip-le.github.io

https://phillip-le.github.io/
1 stars 0 forks source link

Preserving floating point precision in javascript #97

Open phillip-le opened 1 month ago

phillip-le commented 1 month ago

If you're dealing with arithmetic, you probably want to use a dedicated library: https://github.com/MikeMcl/big.js

Using a library can have the tradeoff of ongoing maintenance, so let's look at what you might want to consider:

> Number(20)
20
> Number(20.01)
20.01
> Number('h20')
NaN
> Number( 20)
20
> Number(20 )
20
> Number(020)
16
> Number(20e5)
2000000
> Number(0xA)
10
> Number(Infinity)
Infinity
> Number(-Infinity)
-Infinity
> Number("Infinity")
Infinity
> Number('hello')
NaN
> typeof Number('hello')
'number'
> parseFloat('20hhh')
20

Regex is probably your friend