danimohamadnejad's avatar

how to round a float to nearest half or whole?

Hello in my ecommerce application I need to display stars based on average rating so average rating may be 0, 0.5, 1,1.5.....5 I want to round float rating averages to the nearest half or whole number: 0.32 ---->> 0 0.45 ---->>0.5 1.92 ----->2 1.65------>1.5

any offer? please help thank you

0 likes
2 replies
Nakov's avatar
Nakov
Best Answer
Level 73

One thing is wrong in your example I believe. But this: 0.32 ---->> 0 is closer to 0.5 then 0.

So this is the formula that you need:

round(1.65 / 0.5) * 0.5
>> 1.5

round(1.92 / 0.5) * 0.5
>> 2.0
2 likes

Please or to participate in this conversation.