Open In App

math.RoundToEven() Function in Golang With Examples

Last Updated : 13 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can round off the given number to the nearest even integer with the help of RoundToEven() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the RoundToEven() function.

Syntax:

func RoundToEven(a float64) float64
  • If you pass -Inf or +Inf in this function like RoundToEven(-Inf) or RoundToEven(+Inf), then this function will return -Inf or +Inf.
  • If you pass -0 or +0 in this function like RoundToEven(-0) or RoundToEven(+0), then this function will return -0 or +0.
  • If you pass NaN in this function like RoundToEven(NaN), then this function will return NaN.

Example 1:




// Golang program to illustrate how to round
// off the given number to nearest even integer
  
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Using RoundToEven() function
    res_1 := math.RoundToEven(45.98)
    res_2 := math.RoundToEven(-119.98)
    res_3 := math.RoundToEven(math.Inf(-1))
    res_4 := math.RoundToEven(math.NaN())
    res_5 := math.RoundToEven(math.Inf(1))
  
    // Displaying the result
    fmt.Printf("Result 1: %.1f", res_1)
    fmt.Printf("\nResult 2: %.1f", res_2)
    fmt.Printf("\nResult 3: %.1f", res_3)
    fmt.Printf("\nResult 4: %.1f", res_4)
    fmt.Printf("\nResult 5: %.1f", res_5)
  
}


Output:

Result 1: 46.0
Result 2: -120.0
Result 3: -Inf
Result 4: NaN
Result 5: +Inf

Example 2:




// Golang program to illustrate how to round
// off the given number to nearest even integer
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Using RoundToEven() function
    nvalue_1 := math.RoundToEven(59.89)
    nvalue_2 := math.RoundToEven(-7.567)
  
    // Sum of the given numbers
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.2f + %.2f = %.2f",
            nvalue_1, nvalue_2, res)
  
}


Output:

60.00 + -8.00 = 52.00


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads