Home > Blockchain >  How to fix calculation error in go math operations with floats?
How to fix calculation error in go math operations with floats?

Time:02-11

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?

CodePudding user response:

You can try this (2 digits after comma):

fmt.Println(math.Round(f * 100) / 100)
  •  Tags:  
  • go
  • Related