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.