Golang math.Ceil() Function

Golang math.Ceil() function is “used to find the rounded-up or the ceiling value of a decimal number.” It rounds up a floating-point number to the nearest integer. For example, math.Ceil(4.1) returns 5 and math.Ceil(-4.1) returns -4.

Syntax

func Ceil(x float64) float64

Parameters

The Ceil() function takes a float64 value as an input parameter.

Return value

The Ceil() function returns a float64 value, the smallest integer greater than or equal to the input value.

  1. Passing +Inf or -Inf in the Ceil() function will return +Inf or -Inf.
  2. If you pass -0 or +0 in the Ceil() function, it will return -0 or +0.
  3. If you pass NaN in the Ceil() function, it will return NaN.

Example 1: How to Use math.Ceil() function

package main

import (
  "fmt"
  "math"
)

func main() {
  data := 19.25
  result := math.Ceil(data)
  fmt.Println("The Ceiled Value :", result)
}

Output

The Ceiled Value : 20

Example 2: Rounding the infinity using math.Ceil()

package main

import (
  "fmt"
  "math"
)

func main() {
  infty := math.Inf(+1)
  fmt.Println("The ceiling value of +Inf is", math.Ceil(infty))

 // Negative ∞ infinite value
  infnty := math.Inf(-1)
  fmt.Println("The ceiling value of -Inf is", math.Ceil(infnty))
}

Output

The ceiling value of +Inf is +Inf
The ceiling value of -Inf is -Inf

Example 3: Rounding the negative value using math.Ceil()

Here is an example of using math.Ceil() function to round a negative value.

package main

import (
  "fmt"
  "math"
)

func main() {
  data := -19.21
  result := math.Ceil(data)
  fmt.Println("The Rounded Value :", result)
}

Output

The Rounded Value : -19

That’s it!

Related posts

Go math.Floor()

Go math.Pow()

Go math.Round()

Go math.Min()

Go max int