0

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

3
  • 6
    I know this is a duplicate (I answered it at some point), but you realize 7.28 and 7.0028 will both end up with an answer of 28, correct? You'll have no idea what the original floating part was. Commented Aug 18, 2009 at 16:00
  • 2
    can you clarify how you want these two numbers handled: 7.02828 and 7.000002828 Commented Aug 18, 2009 at 16:01
  • How would you want the likes of 0.000000000125657542619998 dealt with? Commented Aug 18, 2009 at 16:20

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

((int)(d * 10000)) % 10000

3 Comments

is not specifically for this number. if you don't know the number of digits behing the dot. 10000 doesn't work.
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.
JIa3ep, the question is tagged with c#. (Actually, for some reason I originally though the question was for Java :-) ).
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.