开发者

iOS round a float

开发者 https://www.devze.com 2023-03-19 19:12 出处:网络
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

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 it's possible set for example 2 decimal digits:

float fRes = 10.0 / 3.0;
// fRes is 3.333333333333333333333333
float fResOk = FuncRound( fRes, 2 );
// fResOk is 3.33

thanks in adva开发者_如何转开发nce


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.


Assuming that you're looking for the correct function to round to a certain number of digits, you'll probably find it easiest to do the following:

fResOk = roundf( fRes*100.0)/100.0;

That will multiply the value by 100 (giving you your 2 digits of significance), round the value, and then reduce it back to the magnitude you originally started with.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号