How can I only get the decimals of a number?

How can I only get the decimals of a number?

You could round the number using math.floor, then subtract the rounded number from the original one.

1 Like

You can use math.fmod that returns the integer part of the number and then the decimal part:

math.modf(10.221) --> 10, 0.221
5 Likes

Just % by 1 and you’ll get the decimal part

local fractional_part = 10.567 % 1
print(fractional_part) --> 0.567
1 Like

math.fmod returns the remainder of trauncated division, did you mean math.modf?


This fails for negative numbers, to fix this use math.modf or math.fmod with the 2nd argument being 1 is closer. -0.25 % 1 returns 0.75. math.fmod(-0.25, 1) returns -0.25.

4 Likes

math.modf() returns the integer and decimal components. @ideasniper only asked for the decimal.

Here is the math documentation for further reference.

I was correcting his reply, as the OP only asked for decimal then select(2, math.modf(x)) or math.fmod(x, 2) should work.


Original edit as it looks like the reply as edited out the part about fmod

fmod stands for floating (point) modulo/modulus as the Lua’s function math.fmod comes from C’s <math.h>.
modf stands for modulo/modulus and fraction, Lua’s math.modf comes (again) from C’s <math.h>.
Reading the doucmentation, the documentation did not say math.fmod only returns the decimal