1

I need to normalise a value (degrees) to have it in some range. I need to get a reminder of division by 360.

func testFunc(t *testing.T) {

    v := -1050.6
    n := int(v / 360)
    f := v - float64(n)*360

    fmt.Printf("f: %v\n", f)
}

The value I expect is -330.6 the value I get is -330.5999999999999. This happens when I do v - float64(n)*360. Is there any way to get rid of this error?

Yura
  • 969
  • 14
  • 33
  • 1
    That is not an error, that is how float64 stores the precision for the value stored. – Inian Feb 10 '22 at 11:41
  • Yup, I know. But is there any way to correctly round it ? – Yura Feb 10 '22 at 11:44
  • 1
    You can round to arbitrary precision: [Golang Round to Nearest 0.05](https://stackoverflow.com/questions/39544571/golang-round-to-nearest-0-05/39544897#39544897) – icza Feb 10 '22 at 11:51
  • Is it only a display problem? Then try this:`fmt.Printf("%.2f\n", v)` – aMike Feb 10 '22 at 14:28
  • You need to read Goldberg's paper from A[i]CM Computing Surveys[/i], Vol 23, No 1, March 1991, ["What Every Computer Scientist Should Know About Floating-Point Arithmetic"](https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf), and visit https://floating-point-gui.de/ – Nicholas Carey Feb 10 '22 at 17:45
  • thanks! I those articles really give a comprehensive answer. My question raised from a goal to keep representativeness. I'm not converting those number but sending forward where it would be better to keep it "nice" – Yura Feb 10 '22 at 20:22

1 Answers1

1

You can try this (2 digits after comma):

fmt.Println(math.Round(f * 100) / 100)
excommunicado
  • 287
  • 1
  • 10