Rounding floating-point numbers
The rounding of a floating-point number to an integer or to a particular precision has to be done properly. The most common error is to cast the floating-point type float64
to an integer type and consider it as well-handled.
An example could be casting the number 3.9999 to an integer and expect it to become an integer of value 4. The real result would be 3. At the time of writing this book, the current version of Go (1.9.2) does not contain the Round
function. However, in version 1.10, the Round
function was already implemented in the math
package.
How to do it...
- Open the console and create the folder
chapter03/recipe03
. - Navigate to the directory.
- Create the
round.go
file with the following content:
package main import ( "fmt" "math" ) var valA float64 = 3.55554444 func main() { // Bad assumption on rounding // the number by casting it to // integer. intVal ...