- Home /
Round to nearest .5?
How do I take a float: x, and round it to the nearest .5? So if x is 5.1324 it would round to 5. But if x is 5.4216 it would round to 5.5 etc.
Answer by Meltdown · Aug 05, 2011 at 04:17 PM
float number = 5.4216f;
number = (float)Math.Round(number, MidpointRounding.AwayFromZero) / 2;
While Graham's answer is perfect in it's simplicity, this caught my attention... Would you $$anonymous$$d to explain what this does?
googeling this, I've come to believe the (float) is type-casting in c#?? can you do this in js with 'as float'? (or am I mixing things up here?)
Some more research told me, this is not misspelled $$anonymous$$athf.Round but it's System.$$anonymous$$ath.Round
But isn't $$anonymous$$ath.Round(number, $$anonymous$$idpointRounding.AwayFromZero) basically the same as $$anonymous$$athf.Round(number)?
Why are you dividing it by 2?? Is this like Grahams idea, just you forgot to multiply number by 2 before Rounding it?
((thanks for making me look into the .net documentation... so far I've kept shying away from it :p ))
Greetz, $$anonymous$$y.
Hi $$anonymous$$y, the difference between $$anonymous$$ath.Round and $$anonymous$$ath.Round with the $$anonymous$$idpointRounding.AwayFromZero enumeration is that when AwayFromZero is specified, and the number is halfway between two other numbers, it is rounded toward the nearest number that is away from zero, ins$$anonymous$$d of being rounded to a zero.
Uhm... not the difference between $$anonymous$$ath.Round and $$anonymous$$ath.Round with $$anonymous$$idpointRounding but $$anonymous$$athf.Round and $$anonymous$$ath.Round with $$anonymous$$indpointRounding...
Weird!! For some reason I don't get e-mail notification if you answer me?! Almost missed your comment about html-tags (you really didn't see it formatted? What browser are you using? this worries me; thought the tags were foolproof...) and if I hadn't checked back here wouldn't have known about it... :( Are you getting notifications about me?
Greetz, $$anonymous$$y.
Your answer
Follow this Question
Related Questions
Rounding to multiples of 0.5 1 Answer
Math.Abs slows down on time.timescale 0 Answers
How I can increase num 1 to num 2 in x time? 1 Answer
Rotate Center Pivot based Object like a Draw Bridge 2 Answers
Round to 0.5, 1.5, 2.5 ... 1 Answer