Question:
I was at an interview, they asked, "in what type of variable is it better to store money," said Float
, they say, speed, that's all. – rejected. The answer to the question "why" did not hear. so that's why "money" can't be stored in a Float
?
Answer:
For money, pennies are important. The loss of any significant figure in the financial sector is unacceptable. Since numbers are stored in binary – almost any decimal non-integer number does not have a finite number of digits after the decimal point. Since we cannot store an infinite number of digits after the decimal point, some of the number is lost.
A simple example: convert 5.1 to binary
The integer part has only 3 digits
5₁₀ = 1*2² + 0*2¹ + 1*2⁰ = 101₂
And here is the fractional…
.1₁₀ = 0*2⁻¹ + 0*2⁻² + 0*2⁻³ + 1*2⁻⁴ + 1*2⁻⁵ + 0*2⁻⁶ + 0*2⁻⁷ + 1*2⁻⁸ + 1*2⁻⁹...
If you take only the first 7 digits (binary) after the decimal point, you get not 0.1
, but 0.09375
Added: Regarding the appropriate types (since the question has a Java tag – examples for it) for storing financial data, as already written in the comments and adjacent answers, there are two approaches:
- Arbitrary-precision types (such as BigDecimal). I didn’t look at the source code, but inside the storage most likely occurs either in strings or arrays of numbers;
- Integer primitive types (int or long). At the same time, finances are stored in variables in indivisible units of measurement (these are not always pennies / cents, in some cases, for example, hundredths of these units should be taken into account)
As always, the choice should be determined by the specifics of the task. Arbitrary-precision types are likely to be processed more slowly than primitives, but in the case of primitives, we need to "remember" what we store in them so that we don't get astronomical amounts when uploading to adjacent systems.