float64 precision

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?

    
asked by anonymous 03.10.2018 / 02:40

1 answer

5

Rounding is done with the function math.Round() . But do not even try to use it to solve the problem you have there.

What you want is accuracy and not precision. Binary floating-point types do not have exactness, they serve for rough calculations only. For monetary values or other types of values that need accuracy the correct one is to use Decimal . People are tempted because rounding seems to solve the problem, but it stays there ready to cause problems.

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

And if you got curious, yeah, most programmers use wrong to work with wrong values in their software.

    
03.10.2018 / 02:49