Skip to content

How to Rounded up or down a Float in Golang ?

RoundFloat rounds a float to a specified precision. Parameters:

  • value: The float to be rounded.
  • precision: The number of decimal places to round to.
  • roundingUp: If true, rounds up. If false, rounds down.

Returns: The rounded float.

func RoundFloat(value float64, precision uint, roundingUp bool) float64 {
	// Calculate the ratio to adjust the precision
	ratio := math.Pow(10, float64(precision))

	// If rounding up, use the math.Round function
	if roundingUp {
		return math.Round(value * ratio) / ratio
	}
	
	// If rounding down, use the math.Floor function
	return math.Floor(value * ratio) / ratio
}

Experience the magic of coding unfold as you execute this code!

package main

import (
	"fmt"
	"math"
)

func RoundFloat(value float64, precision uint, roundingUp bool) float64 {
	ratio := math.Pow(10, float64(precision))

	if roundingUp {
		return math.Round(value*ratio) / ratio
	}

	return math.Floor(value*ratio) / ratio
}

func main() {
	fmt.Println(RoundFloat(3.14159, 3, true))  // 3.142
	fmt.Println(RoundFloat(3.14159, 3, false)) // 3.141

	fmt.Println("Build with love by Adam Nasrudin")
}

Check code here; with go playground, enjoy your code!