开发者

Rounding an Objective-C float to the nearest .05

I want to round the following floating开发者_C百科 point numbers to the nearest 0.05.

449.263824 --> 449.25

390.928070 --> 390.90

390.878082 --> 390.85

How can I accomplish that?


The match the output in your question, you can do the following:

float customRounding(float value) {
    const float roundingValue = 0.05;
    int mulitpler = floor(value / roundingValue);
    return mulitpler * roundingValue;
}

Example:

NSLog(@"Output: %f --> %.2f", 449.263824, customRounding(449.263824));


There's the round() function. I think you need to do this:

double rounded = round(number * 20.0) / 20.0;

As with all floating point operations, since 1/5 is not directly representable as a binary value, you'll see bizarre not quite exact results. If you don't like that, you can use NSDecimalNumber's -decimalNumberByRoundingAccordingToBehaviour: method but it'll be a bit slower.


I know the question is answered but I used the following code:

float unrounded = 2.234;

float decimal = 0.05;
float decimal2 = 1/decimal;
float rounded = (((int)((unrounded*decimal2)+0.5))/decimal2);

For example:

> unrounded = 2.234 
> decimal = 0.05
> decimal2 = 1/0.05 = 20
> 
> rounded:
> 2.234 * 20 = 44.68
> 44.68 + 0.5 = 45.18 
> make an integer: 45 
> 45 / 20 = 2.25


You could use an NSNumberFormatter to carry out rounding and indeed to specify the rounding you require via one of the NSNumberFormatterRoundingMode options. (Search for "NSNumberFormatterRoundingMode" in the above class reference to see the defaults.)

However, as @Jesse states in the comment on your question, there doesn't seems to be any standard form of rounding going on in the examples you're provided.


If it were round to the nearest x, then you could go with:

roundedValue = originalValue + x * 0.5;
roundedValue -= fmodf(roundedValue, x);

As it is, it isn't entirely clear what you want.


Use floor:

#include <math.h>
...
double result = floor(number * 20.0) / 20.0;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜