Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

Casting the float to integer actually just truncates the float value. Let's say the value 2 is represented as 1.999999; in this case, the output would be 1, which is not what you expected.

The proper way of rounding the float number is to use the function that would also consider the decimal part. The commonly used method of rounding is to half away from zero (also known as commercial rounding). Put simply, if the number contains the absolute value of the decimal part which is greater or equal to 0.5, the number is rounded up, otherwise, it is rounded down.

In the function Round, the function Trunc of package math truncates the decimal part of the number. Then, the decimal part of the number is extracted. If the value exceeds the limit of 0.5 than the value of 1 with the same sign as the integer value is added.

Go version 1.10 uses a faster implementation of the function mentioned in the example. In version 1.10, you can just call the  math.Round function to get the rounded number.