Go Down

Topic: From float to seperate INTs - in an elegant manner :-) (Read 1 time) previous topic - next topic


Hi, I stumbing about a bit on this one.... trying to find an elegant solution to converting a float with one decimal place to 3 sperate integer values... so:

float value = 24.8
int a = 2
int b = 4
int c = 8

Thanks for any pointers.


Code: [Select]
float f = 24.8 ;
int a ;
int b ;
int c ;

a = int(f)/10 ; b= int(f)%10 ; c=int((f-int(f))*10) ;


The fraction needs to be rounded, otherwise the .8 will set c=7
Use this:
Code: [Select]



Damn, you're right ! :) Didnt test it. The cause is that 24.8 is (probably) internally stored as 24.7999999... due to the finite limit of representing decimal fractions in binary.

Well, in an effort to keep my pride intact ;) and to keep it "elegant" use the round function for the last bit
Code: [Select]
c=round((f[n]-int(f[n]))*10) ;


May 05, 2012, 02:50 pm Last Edit: May 05, 2012, 03:53 pm by michael_x Reason: 1
"Elegant" would also be to sprintf the float into a char[] with exactly the format you want ("%4.1f"),
and then simply get the individual digits ( - '0' )

BTW: Strictly seen (and visible on machines where float and double are different), there is no float x with ( x == 24.8 )  ;)

Go Up