I base this more or less on some of your comments to others. To get the integer part, the solution must use modf . But the integer part 1.2 / 0.4 may well be 2 , not 3 ; 0.4 does not appear in a machine floating point (most of them, at least), so you are sharing something very close to 0.4 .
The real question is what you really want. If you are looking to discretize (does such a word exist) depending on bucketSize , then the correct way to do this is to use scaled integers:
int value = 12; int bucketSize = 4; int bucketId = value / bucketSize;
and then:
std::cout << "bucketId as double: " << bucketId / 10.0 << std::endl; std::cout << "bucketId as int: " << bucketId / 10 << std::endl;
Otherwise, if you want to keep the values as doubles, you must decide how close is to convert to int , then use your own function:
int asInt( double d ) { double results; double frac = modf( d, &results ); if ( frac > 1.0 - yourEpsilonHere ) { results += 1.0; } return results; }
You decide which value is appropriate for yourEpsilonHere ; it depends on the application. (Once I used this method, we used 1E-9 . This does not mean that it is suitable for you, however.)
source share