Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Round Even a number in Go (Golang)

Posted on March 25, 2020March 25, 2020 by admin

Table of Contents

  • Overview
  • Code:

Overview

math package of GO provides a RoundToEven method that can be used to round to even a number. It returns the nearest integer rounding ties to even.

Here you can read about use case of RoundToEven – https://mathematica.stackexchange.com/questions/2116/why-round-to-even-integers/2120


Below is the signature of the function. It takes input a float and also returns a float.

func RoundToEven(x float64) float64


Some special cases of RoundToEven function are

  • RoundToEven(±0) = ±0
  • RoundToEven(±Inf) = ±Inf
  • RoundToEven(NaN) = NaN

Code:

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.RoundToEven(0.5)
    fmt.Println(res)

    res = math.RoundToEven(1.5)
    fmt.Println(res)

    res = math.RoundToEven(2.5)
    fmt.Println(res)

    res = math.RoundToEven(3.5)
    fmt.Println(res)

    res = math.RoundToEven(4.5)
    fmt.Println(res)
}

Output:

0
2
2
4
4
  • go
  • math
  • round even
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme