Thursday, March 25, 2010

Trimming float value

Some times we may need a float value 2.345 instead of complete float value 2.345768.
So we need to trim the float value. Below is the function that can do for us

function name: trimFloat( )
param1: float f; the original float value , i.e., 2.345768
param2: int decimals; how many number of digits we want after the point (.)
return: It returns the trimmed float value

float trimFloat(float f, int decimals)
{
char valueStr[20] = {NULL};
sprintf(valueStr, "%f", f);

int i=0, d=0, sign=0;
float val = 0.0f;
float pow = 1.0f;

int length = strlen(valueStr);
if (length <= 0)
return 0;

//omit spaces if any
for (i = 0; isspace(valueStr[i]); ++i)
continue;

//check weather flost value is negative or positive
sign = (valueStr[i] == '-') ? -1 : 1;
if (valueStr[i] == '-' || valueStr[i] == '+')
++i;

//get the value and store it in val
for (val = 0.0f; isdigit(valueStr[i]); ++i)
val = 10.0f * val + valueStr[i] - '0';

//if '.' is occur, just traverse it
if (valueStr[i] == '.')
++i;

//now "d for (pow = 1.0f, d=0; isdigit(valueStr[i]) && d {
val = 10.0f * val + valueStr[i] - '0';
pow *= 10;
}

//return result
return sign * val / pow;
}

The same function we can use for trimming double ( when we trimming double, then 'val' and 'pow' are double data types in the above program).

Note:
I have tested it on VS2003 and its giving exact values i.e., 2.34 / 2.345 / 2.3457 depending on 'decimals' variable.
In VS2005, its giving 2.340000 / 2.345000 / 2.345700.

No comments: