Example: If I have 7.2828, I just want to get the 2828 as an integer.
views:
253answers:
5If d
is the original value, just do the following.
((int)(d * 10000)) % 10000
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.
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.
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.
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.