Round float to 2 decimal places

yourbasic.org/golang

Float to string

To display the value as a string, use the fmt.Sprintf method.

s := fmt.Sprintf("%.2f", 12.3456) // s == "12.35"

The fmt cheat sheet lists the most common formatting verbs and flags.

Float to float

To round to a floating-point value, use one of these techniques.

x := 12.3456
fmt.Println(math.Floor(x*100)/100) // 12.34 (round down)
fmt.Println(math.Round(x*100)/100) // 12.35 (round to nearest)
fmt.Println(math.Ceil(x*100)/100)  // 12.35 (round up)

Due to the quirks of floating point representation, these rounded values may be slightly off.

Float to integer value

Round float to integer value has further details on how to round a float64 to an integer (away from zero, to even number, converted to an int type).

Before Go 1.10

The math.Round function was introduced in Go 1.10. See Round float to integer value for equivalent code.

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: