Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

rounding float

Status
Not open for further replies.

bobetko

Programmer
Jan 14, 2003
155
0
0
US
This example is from this forum. Posted by Salem.

Code:
#include <stdio.h>
#include <math.h>

typedef float type;

type RoundVal(type num)
{
    printf("Input:%f\n", num);
    num *= 100;
    printf("step 1:%f\n", num);
    num += 0.5;
    printf("step 2:%f\n", num);
    num = floor( num );
    printf("step 3:%f\n", num);
    num /= 100.0;
    printf("step 4:%f\n", num);
    return num;
}

int main () {
    type a = 234.456789;
    printf( "Old=%f, new=%f\n", a, RoundVal(a) );
    return 0;
}

Solution is obvious, but doesn't work. Can somebody (Salem) take a look at this.

Here is the result:

Input:234.456787
step 1:23445.679688
step 2:23446.179688
step 3:23446.000000
step 4:234.460007
Old=234.456787, new=234.460007
I tried several numbers and I never gor correct number.
For some numbers I would get 234.4699998 ... etc...
Something is wrong with division part.

Thanks

 
I'd cast to int i step 3. That will eliminate the residual decimals.

Cheers,
Dian
 
Perhaps
Code:
  printf( "Old=%f, new=%.2f\n", a, RoundVal(a) );
Result
Old=234.456787, new=234.46


Remember, floats are always approximations.
Whatever seems perfectly reasonable from a mathematical point of view doesn't mean that any actual computer doing the same thing in floating point arithmetic will deliver the same answer.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top