Go: Round float to 2 decimal places
String
To display the value as a string, use the fmt.Sprintf
method.
s := fmt.Sprintf("%.2f", 12.3456) // s == "12.35"
The Print with fmt cheat sheet lists the most common formatting verbs and flags.
Float
To round to a floating-point value, use one of these techniques:
f := 12.3456
fmt.Println(math.Floor(f*100)/100, // 12.34 (round down)
math.Round(f*100)/100, // 12.35 (round to nearest)
math.Ceil(f*100)/100) // 12.35 (round up)
Due to the quirks of floating point representation, these rounded values may be slightly off.
The math.Round
function will be introduced in Go 1.10. The article Round float to nearest int contains equivalent code.
Comments
Be the first to comment!