Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding an Objective-C float to the nearest .05

I want to round the following floating point numbers to the nearest 0.05.

449.263824 --> 449.25

390.928070 --> 390.90

390.878082 --> 390.85

How can I accomplish that?

like image 914
Yasir Siddiqui Avatar asked Apr 15 '11 14:04

Yasir Siddiqui


2 Answers

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));
like image 200
Black Frog Avatar answered Sep 23 '22 07:09

Black Frog


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.

like image 42
JeremyP Avatar answered Sep 23 '22 07:09

JeremyP