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.
Aug 05 '11 at 04:02 PM
Aug 05 '11 at 07:47 PM
float number = 5.4216f;
number = (float)Math.Round(number, MidpointRounding.AwayFromZero) / 2;
Aug 05 '11 at 04:17 PM
While Graham's answer is perfect in it's simplicity, this caught my attention... Would you mind 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 Mathf.Round but it's System.Math.Round But isn't Math.Round(number, MidpointRounding.AwayFromZero) basically the same as Mathf.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 ))
Hi Ky, the difference between Math.Round and Math.Round with the MidpointRounding.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, instead of being rounded to a zero.
Uhm... not the difference between Math.Round and Math.Round with MidpointRounding but Mathf.Round and Math.Round with MindpointRounding...
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?
multiply it by 2, round, then divide by 2???
Aug 05 '11 at 04:12 PM
Graham Dunnett ♦♦
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
Once you sign in you will be able to subscribe for any updates here
Answers and Comments
The best place to ask and answer questions about development with Unity. Check out our FAQ for more information.
To help users post good questions and use the site effectively we have posted a tutorial video. Please check it out.
asked: Aug 05 '11 at 04:02 PM
Seen: 11620 times
Last Updated: Aug 05 '11 at 09:22 PM
Rounding to multiples of 0.5
"bleeding" when using configurable joints
Math.round not work
How can I round a number?
Float to Int
Determinism problems: Mathf, Unity.Random VS Math, System.Random
Making an enemy face the Player
Distance in a Trajectory of a projectile
How do I find the inverse cosine ???
Why does Mathf.Sign(0.0f) return 1?