Round float to 2 decimal places


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.


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.

Before Go 1.10

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

More code examples

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

Share this page: