5

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!

Roger
  • 59
  • 1
  • 4
  • 1
    What would be a desired result for `3.4444444`? – zerkms Aug 28 '18 at 00:24
  • 1
    3.4444444 rounded to a single decimal point is 3.4, not 3.5. Why do you want code that breaks math? What does 3.644445 "round" to? 3.7? 3.6? 3.65? If what you're doing makes sense, you need to describe it in proper detail, and don't call it "rounding", since obviously that's not what it is. – Jonathan Hall Aug 28 '18 at 06:58

1 Answers1

13

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
Lee
  • 728
  • 7
  • 23
user8774937
  • 183
  • 1
  • 7