Golang's math library provides a Round
function. However, it rounds the float64 to an int, meaning decimals are lost.
A quick workaround around this would be to multiple the number by the number of decimals you want to save, then round, then divide it back again:
raw := 4.335
rounded := math.Round(raw * 10) / 10
Will give you the desired result.
You may want to create a little helper function to round saving any number of digits:
func roundTo(n float64, decimals uint32) float64 {
return math.Round(n * float64(decimals)) / float64(decimals)
}
Usage:
roundTo(4.2655, 1) // 4.3
roundTo(4.3454, 3) // 4.345