Why don't you use Double and Float to mark money?

Asked 1 years ago, Updated 1 years ago, 125 views

I was told not to use double or float when marking money. Why is that?

I think there must be a good reason, but I don't know why.

java floating-point

2022-09-22 14:25

1 Answers

Because float and double can't accurately express the multiple of 10 that we use to count money. The problem is not just Java, but also any programming language that uses floating points, which stems from the way the computer processes floating points.

IEEE-754 This is how floating points are handled: Floating points consist of one bit for sign, several bits for storing exponents, and the rest of the bits for storing singers. This gives the same number as 1025 * 10^2 and float and double use a multiple of 2 instead of a multiple of 10 as in the previous example (so 164 * 2^-4)

Even in multiples of 10, these notation do not accurately represent the simplest fractions. For example, you can't express 1/3 of a multiple of 10. To express this, we're going to have to store an infinitely large negative number of exponents and infinite quantities of three, and that's impossible. However, in most scenarios, you only need to save up to 10^-2 so it's not that bad.

There are also fractions that cannot be accurately represented as multiples of 2, just as multiples of 10 do not represent some fractions. In fact, among the fractions of 100 between 0/100 and 100/100 (important for counting money), there are only five floating points that can be accurately expressed as IEEE-754: 0, 0.25, 0.5, 0.75 and 1. Everything else is a little bit different.

Marking money as double or float may seem okay because it shows only a slight error at first. However, the more you do infinitive calculations with inaccurate numbers, the more accurate you will lose as the error increases. This is why float and double are not suitable for counting money that requires multiples of 10.

In any language, the solution is to count integers in cents. For example, 1025 would be $10.25. Some languages have built-in types that will be used to count money. Among them, Java has the BigDecimal class, and C# has the type.


2022-09-22 14:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.