How to get the remainder of floats? (GDScript)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CEDoromal

I’m trying to get the decimal part only of my number by trying to divide it to 1 and getting the remainder.

This is how I tried it:

answer = somefloat%1

However it gives me an error saying Invalid operands 'float' and 'int' in operator '%'.

So I also tried turning ‘1’ into float:

answer = somefloat%1.0

Then it gave me this Invalid operands 'float' and 'float' in operator '%'.

Can someone please tell me any other solutions for this?

You’re not looking for the reciprocal. The reciprocal of a number is the number that, when multiplied by that number, will give 1.

jandrewlong | 2019-07-18 14:30

Oops… Yeah… Sorry. I was meant to say remainder, not reciprocal. lol

Will edit now… :stuck_out_tongue:

CEDoromal | 2019-07-18 22:34

:bust_in_silhouette: Reply From: CEDoromal

Nevermind… I got the answer. Though I don’t know if this is the best way to do it.

Apparently ‘%’ operator can’t deal with floats so to get the decimal part only I used this:

answer = somefloat - int(somefloat)

By using int(), it automatically gets rid of the decimal part so when you subtract it to the ones with a decimal value, you could get rid of the integer part.

:bust_in_silhouette: Reply From: Zylann

Maybe modf is what you are looking for @GDScript — Godot Engine (3.1) documentation in English

Ooh… I didn’t know that existed… Thanks!

CEDoromal | 2019-07-18 22:38

For those of us in the future, the function is really fmod

ichster | 2022-05-23 20:04