Finding the Ceiling Value of Specified Number in Golang


In programming, we often come across situations where we need to round off a given number to the nearest whole number. This is where the concept of ceiling comes into play. In Golang, we can use the built-in math package to find the ceiling value of a specified number.

Ceiling Value

The ceiling value of a number is the smallest integer greater than or equal to that number. For example, the ceiling value of 3.2 is 4, the ceiling value of 6 is 6, and the ceiling value of -2.6 is -2.

The ceiling value of a number x is denoted by ceil(x). It can be defined mathematically as ceil(x) = min{m ∈ ℤ | m ≥ x}. This means that the ceiling value of x is the smallest integer m such that m is greater than or equal to x.

Finding Ceiling Value in Golang

Golang provides a built-in math package that has a ceil() function to find the ceiling value of a specified number. The function takes a float64 type number as input and returns a float64 type number which is the smallest integer greater than or equal to the input number.

Syntax 

Here's the syntax of the ceil() function −

func Ceil(x float64) float64

The ceil() function takes a float64 type number as input and returns a float64 type number which is the smallest integer greater than or equal to the input number.

Example 1

Let's find the ceiling value of the number 3.2.

package main

import (
   "fmt"
   "math"
)

func main() {
   fmt.Println(math.Ceil(3.2))
}

Output

4

In this example, we have imported the math package and used the ceil() function to find the ceiling value of the number 3.2.

Example 2

Let's find the ceiling value of the number -2.6.

package main

import (
   "fmt"
   "math"
)

func main() {
   fmt.Println(math.Ceil(-2.6))
}

Output

-2

In this example, we have used the ceil() function to find the ceiling value of the number -2.6.

Example 3

Let's find the ceiling value of the number 7.

package main

import (
   "fmt"
   "math"
)

func main() {
   fmt.Println(math.Ceil(7))
}

Output

7

In this example, we have used the ceil() function to find the ceiling value of the number 7.

Conclusion

The ceil() function provided by the math package in Golang helps in finding the ceiling value of a specified number. It is a useful tool when working with decimal numbers and we need to round off the number to the nearest integer.

Updated on: 12-Apr-2023

665 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements