Round all decimal points in Golang

Viewed 7026

I'm trying to unconventionally round all the digits in a float64 variable. For example:

3.4444445 --> 3.5

I want to do this without converting it into a string!

1 Answers

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*math.Pow(10, float64(decimals))) / math.Pow(10, float64(decimals))
}

Usage:

roundTo(4.2655, 1) // 4.3
roundTo(4.3454, 3) // 4.345
Related