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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With