سؤال

How can I transform rational numbers like 1.24234 or 45.314 into integers like 124234 or 45314 also getting the number of decimal digits?

هل كانت مفيدة؟

المحلول

Convert to a string

Find the position of the decimal point.

Subtract that from the length of the above string, for the number of decimals.

Then take the point out of the string.

نصائح أخرى

int i=0;
float a = 1.24234;

for(i; i<20; i++){
    float b=pow(10,i);
    if((a*b)%10==0)
        break;
}
int c = pow(10,i-1);
int result = a*c;

I think this code will help you.

If your number is W.D (Whole.Decimal)

To get W just do (int)W.D. To get D you can do W.D - (int) W.D

Now you have your whole number and your decimal point separated. To figure out your x10 multiplier on your W keep dividing D by 10 until you get a result that is less than 10.

Now: WxN+D (where N is the number of times you divided by 10)

Note: I didn't write the code as an example, because I feel this may be a homework assignment. Also, if you are using very long (ie: precise floating points) this won't hold, and could likely overflow. Check your bounds before implementing something like this.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top