skip to Main Content

I’m new to Golang but i found a strange behavior (and correct me if i am wrong)
The function math.RoundToEven() supposed to return a rounded even number but unexpectedly it returns odd number

I am running Golang 1.21.6 on ubuntu machine
I have reported the issue on Golang github issues,but the answer was strange!!
the issue on github

Any idea what is the problem
Do u think this is a bug!!!!!!?

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.RoundToEven(17.1))
      //answer supposed to be 18 but it returned 17!!!
}

2

Answers


  1. RoundToEven returns the nearest integer, rounding ties to even (a tie is essentially exactly half way between two whole numbers, so .5). Which is a confusing statement, so an example to demonstrate:

    • 11.4 rounds to 11.0
    • 11.5 rounds to 12.0
    • 11.6 rounds to 12.0
    • 12.4 rounds to 12.0
    • 12.5 rounds to 12.0
    • 12.6 rounds to 13.0
    Login or Signup to reply.
  2. If you want a function that actually rounds to even numbers only, use the following:

    func roundToEven(f float64) float64 {
        return math.Round(f/2) * 2
    }
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search