0

I have the following:

package main

import (
    "fmt"
    "math"
)

func main() {
    nums := []float64{
        0.15807659924030304, 0.10901273787021637, 0.04955724626779556, 0.05886702239513397,
    }

    for _, f := range nums {
        fmt.Println(f, math.Round(f/.0001)*.0001)
    }
}

output is:

0.15807659924030304 0.15810000000000002
0.10901273787021637 0.109
0.04955724626779556 0.049600000000000005
0.05886702239513397 0.0589

Why are some ending up with > 4 decimal places? How do I correct it?

https://play.golang.org/p/kLvVjmsjq6Y

user_78361084
  • 3,538
  • 22
  • 85
  • 147
  • fmt.Println(f, math.Round(f/.0001)/10000) – Vla Mai Jun 03 '18 at 23:17
  • 6
    Basic computer floating point: The *actual* value is stored in binary base-2. What you are displaying is in base-10. Any value that is not perfectly divisible by 2 cannot be exact in binary floating point. It is never, ever exactly the fraction you think you have. – Zan Lynx Jun 03 '18 at 23:17
  • Possible duplicate of [Golang Round to Nearest 0.05](https://stackoverflow.com/questions/39544571/golang-round-to-nearest-0-05/39544897#39544897). – icza Jun 04 '18 at 05:41

1 Answers1

4
        fmt.Printf("%f %b %0.4f\n", f, f, math.Round(f/.0001)*.0001)

Try using that. The %0.4f will format it to 4 decimal places. In fact if you only need the string, use that instead of your Round function.

The %b will show you the real value. In Go that will display a large decimal (base-10) value, a p, then the exponent in powers of 2. So when it displays 5695309707476992p-55 you can find the floating point by doing 5695309707476992 / 2^55

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131