The math.Floor() function in Golang is “used to find the rounded-down or the floor value of a decimal number“.
Syntax
func Floor(x float64) float64
Parameters
x: The function accepts only one argument of type float64.
There are some exceptions I would like to mention here.
- Inf: If you pass an infinite value(±Inf), the return value will be the same as the argument.
- NAN: If you pass a NAN value, it returns NAN.
- 0: If you pass the (±)0 argument, it returns the same value as an argument.
Return value
The Floor() function returns a single value of the argument rounded down to the nearest whole number whose data type is float64.
Example 1: Use of math.Floor() function
To use the math.Floor() function, import a math package.
package main
import (
"fmt"
"math"
"reflect"
)
func main() {
var floating_point = 19.21
fmt.Println(floating_point)
fmt.Print("The data type is: ", reflect.TypeOf(floating_point), "\n")
var rounded_down = math.Floor(floating_point)
fmt.Println(rounded_down)
fmt.Print("The data type is: ", reflect.TypeOf(rounded_down), "\n")
}
Output
19.21
The data type is: float64
19
The data type is: float64
We declared a float64 value in this example and printed its data type using the reflect.TypeOf() function.
Using math.Floor() function, we rounded a value from 19.21 to 19. Although an output value seems like an integer, it is float64 as we printed its data type after conversion.
Example 2: Passing Inf, NAN, and 0
Inf means infinite value, and NAN means not a number and 0. Inf can be positive or negative.
package main
import (
"fmt"
"math"
)
func main() {
var infinity = math.Inf(-1)
var notANumber = math.NaN()
var zero = 0
fmt.Println(infinity)
fmt.Println(notANumber)
fmt.Println(zero)
}
Output
-Inf
NaN
0
It returns the same output as the argument passed to the Floor() function.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.