1

Fairly simple question, but I know I'm going to have to clarify - I am NOT talking about doing operations of any kind.

I have some currency values and other decimal values that need to be handled. Is it safe to store them as floats, and when any sort of operation needs to be done, convert them to integers, and then back to floats (assume I can handle the decimal places). I understand precision errors when doing math with floats, but is there anything explicitly dangerous about simply storing them for ease of use?

Thirk
  • 571
  • 1
  • 7
  • 24
  • 3
    Isn't every number in JavaScript a double? – Kevin Ji Jan 14 '17 at 06:36
  • javascript has one type of number ... Number ... which is a 64bit float ... unless you use Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array or Float32Array of course – Jaromanda X Jan 14 '17 at 06:49
  • I'd say this is pretty safe, BUT, Idk how javascript is about floating point accuracy from operations. For example, http://stackoverflow.com/questions/588004/is-floating-point-math-broken in python you get weird stuff like that. So doing `if(a+b == 0.3)` could be a problem. – Ashwin Gupta Jan 14 '17 at 06:54
  • @AshwinGupta That's the entire idea behind converting to int before operations, I just want to make sure I'm entirely safe doing nothing but storing. – Thirk Jan 14 '17 at 07:03
  • @Thirk oh on that aspect you should be absolutely fine. Just bear in mind that `==` checks for equivalence and `===` checks for type and equivalence. – Ashwin Gupta Jan 14 '17 at 07:04

1 Answers1

1

Any integer between -2^24 and 2^24 can be converted to and from a single-precision floating point number without error; for double-precision, it's -2^54 to 2^54. For that matter, you can do floating-point operations on them without introducing any error, as long as the results are guaranteed to be integers in the same range.

Sneftel
  • 40,271
  • 12
  • 71
  • 104