Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding my decimal float to nearest half or whole number?

Ok im having issues with my calculations in my app and im pretty sure that it is due to the decimals being to long. This is something that needs to be done anyway because it will drastically shortin the ammount of code i need.

below is how i currently have this portion of my code...

float ab1 = [abdomen1Input.text floatValue];
float ab2 = [abdomen2Input.text floatValue];
float ab3 = [abdomen3Input.text floatValue];
float hip1 = [hips1Input.text floatValue];
float hip2 = [hips2Input.text floatValue];
float hip3 = [hips3Input.text floatValue];
float neck1 = [neck1Input.text floatValue];
float neck2 = [neck2Input.text floatValue];
float neck3 = [neck3Input.text floatValue];
float height1 = [heightInput.text floatValue];
float neckAvg;
float abHipAvg;
float cirVal;

(abHipAvg = (((ab1+ab2+ab3)/3)+((hip1+hip2+hip3)/3)));

(neckAvg = ((neck1+neck2+neck3)/3));

(cirVal = (abHipAvg - neckAvg));

what i need to do is round the "abHipAvg" and "neckAvg" to the nearest .5 or .0 .Users are only going to be entering .25 , .5 or .75 but once i divide those by 3 i need to round that answer up or down to the nearest half for the rest of my calculations to work properly. i have tried looking through some questions on here to find a solution because i have seen one similar to this before i just cant remember where or what to type in the search. If anyone can point me in the right direction i would really appreciate it.

like image 350
Shaun Hornsby Avatar asked Feb 24 '23 14:02

Shaun Hornsby


1 Answers

The easiest way is to take your final number, times 2 and round. Then divide by 2.

(abHipAvg = (((ab1+ab2+ab3)/3)+((hip1+hip2+hip3)/3)));
abHipAvg = roundf(abHipAvg * 2.0f) / 2.0f;

and the same with neckAvg.

like image 90
Nicki Avatar answered Mar 15 '23 19:03

Nicki