Decimal value of float

Started by
5 comments, last by Blaster 21 years, 9 months ago
I want to put the non-integer value of a float in an int. For example, stick the 37 from 2.37 in a int. I do this

inline bool as_decimal( const float f )
{
//  I tried this also
//  return( f - float( int( f ) ) != 0.0f );

    return( float( int( f ) ) != f );
}

void partial_code( )
{
    int nInteger = int( f );
    float fDecimal = f - float( nInteger );

    while( as_decimal( fDecimal ) )
    {
        fDecimal *= 10.0f;
    }
}
 
But (probably because of floating point accuracy, or convertion rounding) as_decimal doesn't work. Any idea? ---------------- Blaster Computer game programmer and part time human being Strategy First - http://www.strategyfirst.com BlasterSoft - http://www.blastersoft.com [edited by - Blaster on July 18, 2002 4:03:17 PM]
Advertisement

  const int getDecimals( const float& f){	float tempF;	tempF = f - int(f); // remove non decimal part		while (1)	{		tempF *= 10.0f;		if (tempF - int(tempF) == 0.0f)break;	}	return int(tempF);}  


that''s my suggestion, you might want to make it allittle safer than while(1) though...
---GUI Programming Division Manager at Wildfire Gamesworking on the 0 A.D. project
Haha yeah, that''s pretty much how yours look too... Mmm, it is no good you''re right...
---GUI Programming Division Manager at Wildfire Gamesworking on the 0 A.D. project
That''s already what I do (mostly).
But the if in the while is always true, even if the float is 37.0.

----------------
Blaster
Computer game programmer and part time human being
Strategy First - http://www.strategyfirst.com
BlasterSoft - http://www.blastersoft.com

ah, too lazy (and tired) to look for errors
in your code.

just thought..

hhhmmm...

float f = 123.456;

int integer = (int) f;
float decimal = f - float(integer);

while ( decimal > (float) int(decimal) )
{decimal *= 10;}

int dec = (int) decimal;


having a second look at your code, mine
looks very much like what you did.
copy, paste, and try this, if it works, be happy,
if not, hhmmm, dunno.

I''ll go to bed in 1/2 hr or so...
tired...

sorry








Sprintf() the float into a string then search for the the decimal. Put everything to the right of the decimal into a new string the atol() the new string into your int.

I''d write out the code, but my break just ended.
The major difficulty is that sticking the numbers right of the decimal place into an integer is not often a worthwhile thing to do.

Consider 8.6 and 3.189923453879. The latter would produce a much huger (is that a word? now it is!) fractional part, despite the fact that it''s actually smaller.

If you want to extract a certain predefined number of decimal places, that would make much more sense. I suggest:

float f = 23.45;
int ipart = (int) f;
int fpart = ((int)(f-ipart))*pow(10,2); // extract two digits


Don''t listen to me. I''ve had too much coffee.

This topic is closed to new replies.

Advertisement