views:

50

answers:

4

I need to do the following equation floor(e%100000) where e is a double. I know mod only accepts int values, how do I go about achieving this same result?

Thanks

+3  A: 

Why don't you take the floor first, then mod, ie. floor(e) % 100000 ?

Perhaps I've misunderstood what you're trying to achieve. Could you give an example of the input and output you expect?

Evgeny
I'm converting an easting and northing in metres with a huge decimal number (converted from a lat/long) into metres and then formatting it.
churchill614
This should be more or less equivalent to any other solution here.
Merlyn Morgan-Graham
This works only as long as the result of `floor` fits in an integer type. For extremely large floating point numbers, you need `fmod` (and need to hope it's implemented in a way that's accurate for huge numbers), but if you're using `fmod` with large numbers you're probably misusing floating point and going to run into some nasty loss-of-precision bugs.
R..
+3  A: 

use fmod

Anders K.
+2  A: 

Use the fmod() function instead of %. It accepts double parameters, and returns a double result.

slacker
A: 

You could use division to make the equivalent of modulo:

double e = 1289401004400.589201;
const double divisor = 100000.0;
double remainder = e - floor(e / divisor) * divisor;
double result = floor(remainder);
printf("%f\n", result);

This prints

4400.000000

Of course, this is much slower than any built-in modulo...

You could also just use fmod, as Anders K. suggested :)

Edit

Fixed std::cout (C++) reference to use printf (C). Fixed change to output. Now it is purely C.

Merlyn Morgan-Graham
-1 for `cout` in a question tagged C that even says C in the subject. C is not C++.
R..