modf()
The math.modf()
function is a part of the Lua math
library and is used to split a given number into its integral and fractional parts. It rounds the number down to the nearest integer and returns both the integer part and the fractional part as separate values.
Note:
math.modf()
rounds the number down and always returns a value equal to or less than the given number.
Syntax
As modf()
is a method that is a part of the standard Lua math
library, it must be called as math.modf()
.
integerPart, fractionalPart = math.modf(number)
math.modf()
returns the integral part of number
in integerPart
and the fractional part in fractionalPart
.
Example 1
To find the integral and fractional parts of a number:
local num = 5.3local integerPart, fractionalPart = math.modf(num)print("Integer part: " .. integerPart)print("Fractional part: " .. fractionalPart)
This results in the following output:
Integer part: 5Fractional part: 0.3
Example 2
When math.modf()
is used with a number that is already an integer:
local num = 8local integerPart, fractionalPart = math.modf(num)print("Integer part: " .. integerPart)print("Fractional part: " .. fractionalPart)
This results in the following output:
Output: Integer part: 8Output: Fractional part: 0.0
Example 3
For negative numbers, math.modf()
returns the closest integer greater than or equal to the given value:
local num = -3.3local integerPart, fractionalPart = math.modf(num)print("Integer part: " .. integerPart)print("Fractional part: " .. fractionalPart)
This results in the following output:
Integer part: -3Fractional part: -0.3
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours