Round float to 2 decimal places
source link: https://yourbasic.org/golang/round-float-2-decimal-places/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Round float to 2 decimal places
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 common tasks is a collection of handy code examples.
Share:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK