Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding down a float to nearest 0.5 in Objective C / Cocoa Touch

I want to round a floating point number down such that I get that will be anywhere between 0.5 and 7 (with any number of decimals) while rounding anything below 0.5 up to 0.5.

For example,

0.1, 0.11442, 0.46 would all be 0.5.
1.1, 1.43, 1.35 would all be 1.
1.56, 1.6, 1.8 would all be 1.5.

Anything over 5 will be rounded down to 5.

The final data set I want is 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5.

I don't know any functions that round down for Objective C, without it being to whole numbers.

like image 539
Biggs Avatar asked Apr 21 '13 14:04

Biggs


1 Answers

floor() will round down floating point numbers to the next integer. If you first multiply by 2, round down, then divide by two, you will get the desired result.

float rounded = value < 0.5f ? 0.5f : floorf(value * 2) / 2;
like image 91
DrummerB Avatar answered Sep 30 '22 16:09

DrummerB