iOS round a float

前端 未结 2 1504
离开以前
离开以前 2021-02-18 19:43

I have a floating point number that have more decimal digits, for example:

float fRes = 10.0 / 3.0;

actually the fRes value is 3.3333333333333

2条回答
  •  太阳男子
    2021-02-18 20:12

    I don't know where you are using this rounded number, but you should only round your value when displaying it to the user, there are C based format string ways to round floating point numbers for example

    [NSString stringWithFormat:@"%.2f", value];
    

    as you may have already read, floating point number are approximations of real numbers, so doing fResOk = roundf( fRes*100.0)/100.0; may not give you 3.33 but a number which is just as close as you can get with floating point number to 3.33.

提交回复
热议问题