math.modf() function in Lua programming

LuaServer Side ProgrammingProgramming

There are several occurrences when we want to get the integer value of a number and also the fractional value that the number has if any, so that we can use either or both of these values.

Lua provides us with a math.modf() function that we can use to find the integer value along with the fractional value if the number has any.

Syntax

math.modf(number)

The math.modf() function returns two values when we call the function, the first value is the integer value of the number and the second returned value is the fractional value of the number if it has any.

Example

Let’s consider a simple example where we will make use of the math.modf() function in Lua −

Live Demo

a, b = math.modf(3.3)
c, d = math.modf(7.1)
print(a, b)
print(c, d)

Output

3    0.3
7    0.1

It should be noted that if we try to find modf of a number which is already the closest integer to itself then we will get the same number as the output.

Example

Consider the example shown below −

Live Demo

e, f = math.modf(8)
print(e, f)

Output

8     0.0

We can also pass negative numbers in the math.modf() function as an argument.

Example

Consider the example shown below −

Live Demo

g, h = math.modf(-3.3)
print(g, h)

Output

-3    -0.3
Published on 19-Jul-2021 11:56:57