Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

🎠 Round float to any precision in Go

introduction numbers math

Please consider supporting us by disabling your ad blocker

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:

  1. multiply the number to be rounded times 10 to the power of X, where X is the precision you want to achieve
  2. round this raised number to the nearest integer value using the math.Round() function
  3. divide the rounded number by 10 to the power of X, where X 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

🧊 Cube root in Go

shorts numbers math

🟦 Square root in Go

shorts numbers math

🍰 The maximum and minimum value of the int types in Go

shorts numbers math