tags:

views:

253

answers:

5

Example: If I have 7.2828, I just want to get the 2828 as an integer.

+3  A: 

If d is the original value, just do the following.

((int)(d * 10000)) % 10000
avakar
is not specifically for this number. if you don't know the number of digits behing the dot. 10000 doesn't work.
jmayor
In C++ you should use static_cast to cast double to int. Final code should look like static_cast<int>(d*10000.0)%10000. C-cast is only for compatibility. Please, don't use it without reason.
Kirill V. Lyadvinsky
JIa3ep, the question is tagged with c#. (Actually, for some reason I originally though the question was for Java :-) ).
avakar
A: 

You might want to look at my DoubleConverter code. It doesn't immediately do what you want, but with a bit of fiddling it should work. Admittedly that's basically doing the string manipulation itself, but you may still learn what you want to know.

Jon Skeet
+3  A: 

Decimal is your friend...

Convert your number to a decimal and then do this.

       decimal d = (decimal)7.2828;
       int val = decimal.GetBits(d - decimal.Truncate(d))[0];

the neat thing about a decimal is that it stores the val as an int, and then just stores a decimal point position.

Brian Rudolph
A: 

In C++, use double modf(double, double *):

double value;
double fractional_part;
double integer_part= modf(value, &fractional_part);
int fractional_part_as_integer= fractional_part * 10000; // insert appropriate scale here.
MSN
A: 

I don't think you can. Most CPUs cannot represent 7.2828 as a double (IBM mainframes being the exception). The reason is that they represent doubles as a sum of powers of 2. The "7" part is easy: 1+2+4. The fracational bit is harder: 0.25+0.0.03125+0,0009765625..... - an infinite sequence. For practical reasons, this sequence is truncated. And the resulting double will be close to 7.2828. Perhaps 7.282800000000001245. This probably won't fit into an (32 bits) integer.

MSalters