jodohutu
jodohutu

Reputation: 31

Is parseFloat safe in JavaScript?

In databases for store prices shouldn't use float type (should be decimal). So is in JavaScript parseFloat() safe for prices?

For example I have array with 1000000 numbers and I would like parse all to float and do various operations throughout the set and in the whole.

Upvotes: 0

Views: 2163

Answers (1)

nwellnhof
nwellnhof

Reputation: 33638

It depends on what you mean by "safe", but in general you shouldn't use floating-point math for prices. parseFloat only guarantees that the resulting floating-point number is the nearest IEEE double according to "round to nearest, ties to even" rounding mode. In most cases, this will result in a small rounding error:

> parseFloat("0.11").toFixed(40)
< "0.1100000000000000005551115123125782702118"

Further mathematical operations will increase the rounding error. If you make sure to round the final result to two decimal places with toFixed(2), you should get the expected result in most cases. But this isn't guaranteed:

> parseFloat("1.37") * 90 * 90 * 90 * 90 * 90 * 90 * 90 * 90
< 5897400777000001

Unless you really know what you're doing, work with integer values of the smallest currency unit to be on the safe side. Note that JavaScript's number type can only store integers up to 253 exactly.

Upvotes: 1

Related Questions