Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

What is the Modf function in Golang?

Faraz Karim

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
}

RELATED TAGS

golang
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring