I understand float/double are bad choices for storing money amounts. When you do some arithmetic operations, you may lose precision.
Is it safe to use float just to represent the amount when arithmetic operations are not performed on that number? For example, mapping amount from API to float type.
CodePudding user response:
Not necessarily. Most numbers that "look nice" in base-10 representation, such as 0.1, can not be represented exactly as a binary floating-point number. For example, even when using double, the base-10 number 0.1 will be represented as a number that is approximately 0.1000000000000000055511151231257827021181583404541015625.
Only decimal numbers that can be written as a sum of inverse powers of two (1/2, 1/4, 1/8, 1/16, and so on) can be represented exactly (for example, 0.9375, the sum of those four numbers). This is similar to the situation with base-10 numbers; it just happens for more numbers in binary. For example, 1/3 cannot be represented with a finite number of decimals in either base-10 or binary.
However, if you're just storing the number and printing it at some point, you'll probably be fine, because most functions for printing floating-point numbers will round the number off nicely for you.
CodePudding user response:
I know a commercial company that uses some kind of double variables in their database to represent money count, and I even know cases where their values differ by 245,20 -> 245,1999999999999999999999 because of that so that should be fine for a learning purpose at least. Just use math.round(value, precision(2)) or whatever math functions / methods for rounding a value java has.
