Go Down

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

point5

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
becomes
int a = 2
int b = 4
int c = 8

Thanks for any pointers.

Msquare

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) ;

el_supremo

The fraction needs to be rounded, otherwise the .8 will set c=7
Use this:
Code: [Select]
c=int((f-int(f)+0.05)*10);

Pete

Msquare

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) ;

michael_x

#4
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