简体   繁体   中英

Rounding off floating point values

While rounding off the floating point values I observed some discrepancy in values. I have extracted following part of code. Here if variable var_d is assigned value> 5.3 to then I am getting proper values for variable var_d , but for values like 5.01 and 5.02 I am getting 500 and 501 respectively.

#include<stdio.h>
int main()
{
double var_d=5.02;
long var_l;
var_l = (double)(var_d*100);
printf("var_d : %f  var_l= %ld\n ",var_d,var_l);
printf("result : %ld\n",var_l);
return 0;
}

Use

double var_d=5.02;
long var_l = rint(var_d*100);

Since 100 * 5.02 is not not exactly equal to 502, you are getting a rounded down.

To be clearer: 5.02 has no exact representation in binary floating point . Thus var_l*100 == 5.02*100 is not exactly 502. In fact it is closer to 501.99999999999994. When you cast it to an integer, this is rounded down to 501.

float var_d=5.02;
long var_l;
var_l = (long)(float)(var_d*100);

This should works properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM