How do I use modulus for float/double?

ShrimpCrackers picture ShrimpCrackers · Jun 1, 2010 · Viewed 124.4k times · Source

I'm creating an RPN calculator for a school project. I'm having trouble with the modulus operator. Since we're using the double data type, modulus won't work on floating point numbers. For example, 0.5 % 0.3 should return 0.2 but I'm getting a division by zero exception.

The instruction says to use fmod(). I've looked everywhere for fmod(), including javadocs but I can't find it. I'm starting to think it's a method I'm going to have to create?

edit: hmm, strange. I just plugged in those numbers again and it seems to be working fine...but just in case. Do I need to watch out using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).

Answer

RodeoClown picture RodeoClown · Jun 1, 2010

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.