Accuracy of float64

Asked

Viewed 235 times

2

Why Go when performing the calculation:

(1 * 0.09) + 0.36

returns a float64 in the following format 0.44999999999999996?

I’m trying to make comparisons with tests and the calculation should be 0.45 because this behavior and how do I "round" that number?

1 answer

5


Rounding occurs with the function math.Round(). But don’t even try to use it to solve the problem you have there.

What you want is accuracy and not precision. Binary floating point types are not accurate, they serve for approximate calculations only. For monetary values or other types of values that need accuracy the correct is to use the type Decimal. People are tempted because with rounding it seems to solve the problems, but it stands there ready to cause you problems.

To learn more read What is the correct way to use the float, double and decimal types?.

And if you’re curious, yes, most programmers use wrong and work with wrong values in their software.

  • The only problem with this package is that it is not standard, but there is Math/big. I’ve heard that they recommend using an int64 also to represent money. I honestly do not know what the current situation of the language and if they have already solved this problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.