O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter03/recipe03.
  2. Navigate to the directory.
  3. 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 := int(valA)          fmt.Printf("Bad rounding by casting to int: %v\n", intVal)          fRound := Round(valA)          fmt.Printf("Rounding by custom function: %v\n", fRound)        }        // Round returns the nearest integer.        func Round(x float64) float64 {          t := math.Trunc(x)          if math.Abs(x-t) >= 0.5 {            return t + math.Copysign(1, x)          }          return t        }
  1. Execute the code by running go run round.go in the Terminal.
  2. You will see the following output:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required