Mod()

battaniyeligazi's avatar
Published Aug 6, 2023
Contribute to Docs

The Mod() function returns the floating-point remainder of dividing x by y. The result has the same sign as x and a magnitude less than the magnitude of y.

The Mod() function operates exclusively with floating-point numbers.

Note: If the numbers involved in the operation are of integer type, the % modulus operator should be used instead. The % operator works with integers, while math.Mod() operates with floating-point numbers.

Syntax

math.Mod(x,y)

The Mod() function takes two arguments of type ‘float64’.

Please be aware of the following special cases:

  1. If the argument has a +Inf value, the return value will be 0:
  2. If the value of x is either (±)Inf or NAN, the return value will be NaN.
  3. The return value is NAN if the value of the second argument is either 0 or NAN.
  4. If (±)Inf is passed as the second argument, the return value is x (first argument).

Example

The following example demonstrates how to use the Mod() function and print the result:

package main
import(
"fmt"
"math"
)
func main() {
a:= 23.50
b:= 5.20
modResult := math.Mod(a, b)
fmt.Printf("The modulus of %.2f and %.2f = %.2f", a, b, modResult)
}

The output will be:

The modulus of 23.50 and 5.20 = 2.70

Codebyte Example

The provided example is executable and demonstrates special cases in the use of the Mod() function:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Go on Codecademy