To round a floating-point number in Go, you can use the math.Round()
function from the built-in math
package. However, this function rounds to the nearest integer, so it cannot be used directly to round a float to a particular precision. But you can use it to create your own function that rounds to any decimal places. All you need to do is:
- multiply the number to be rounded times 10 to the power of
X
, whereX
is the precision you want to achieve - round this raised number to the nearest integer value using the
math.Round()
function - divide the rounded number by 10 to the power of
X
, whereX
is the rounding decimal precision
In this way, by rounding the raised number to the nearest integer and then dividing, we get a number rounded to the specified decimal places.
Examples
The roundFloat()
is a floating-point rounding function, working as described above. The way it works is shown in the example:
package main
import (
"fmt"
"math"
)
func roundFloat(val float64, precision uint) float64 {
ratio := math.Pow(10, float64(precision))
return math.Round(val*ratio) / ratio
}
func main() {
number := 12.3456789
fmt.Println(roundFloat(number, 2))
fmt.Println(roundFloat(number, 3))
fmt.Println(roundFloat(number, 4))
fmt.Println(roundFloat(number, 5))
number = -12.3456789
fmt.Println(roundFloat(number, 0))
fmt.Println(roundFloat(number, 1))
fmt.Println(roundFloat(number, 10))
}
Output:
12.35
12.346
12.3457
12.34568
-12
-12.3
-12.3456789
Round float to 2 decimal places
Full example of rounding a float to 2 decimal places:
package main
import (
"fmt"
"math"
)
func roundFloat(val float64, precision uint) float64 {
ratio := math.Pow(10, float64(precision))
return math.Round(val*ratio) / ratio
}
func main() {
number := 12.3456789
fmt.Println(roundFloat(number, 2))
}
Output:
12.35
Round float to 3 decimal places
Full example of rounding a float to 3 decimal places:
package main
import (
"fmt"
"math"
)
func roundFloat(val float64, precision uint) float64 {
ratio := math.Pow(10, float64(precision))
return math.Round(val*ratio) / ratio
}
func main() {
number := 12.3456789
fmt.Println(roundFloat(number, 3))
}
Output:
12.346