What is the Modf function in Golang?

The Modf function is used to find the integer and fractional part of a floating-point number.

To use this function, you must import the math package in your file and access the Modf function within it using the . notation (math.Modf). Here, Modf is the actual function, while math is the Go package that stores the definition of this function.

Function definition

The definition of the Modf function inside the math package is as follows:

Parameters

Modf takes a single argument of type float64 whose whole number and fractional parts are to be returned.

Return value

The Modf function returns two values of type float64:

  • int: The integer part of the passed parameter.

  • frac: The fractional part of the passed parameter.

Some special return cases:

  • If (±)Inf is passed as an argument, then Modf returns (±)Inf and NAN.

  • If the argument passed is NAN, then Modf returns NAN and NAN.

Code

Below is a simple example where we find out the integer and fractional parts of 3.34563.3456.

package main
import(
"fmt"
"math"
)
func main() {
var x float64 = 3.3456
var w,z float64 = math.Modf(x)
fmt.Print("For ", x," integer part: ", w, " fractional part: ",z)
}

The example below demonstrates how the Modf function handles a NAN value in its argument.

Here, we use the NaN function present in the math package to generate a NAN value.

package main
import(
"fmt"
"math"
)
func main() {
var x float64 = math.NaN()
var w,z float64 = math.Modf(x)
fmt.Print("For ", x," integer part: ", w, " fractional part: ",z)
}

Free Resources