x


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.

more ▼

asked Aug 05 '11 at 04:02 PM

NinjaSquirrel gravatar image

NinjaSquirrel
759 31 41 69

(comments are locked)
10|3000 characters needed characters left

2 answers: sort newest
float number = 5.4216f;
number = (float)Math.Round(number, MidpointRounding.AwayFromZero) / 2;
more ▼

answered Aug 05 '11 at 04:17 PM

Meltdown gravatar image

Meltdown
5.6k 18 25 49

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 ))

Greetz, Ky.

Aug 05 '11 at 07:46 PM SisterKy

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.

Aug 05 '11 at 07:58 PM Meltdown

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?

Greetz, Ky.

Aug 05 '11 at 09:21 PM SisterKy
(comments are locked)
10|3000 characters needed characters left

multiply it by 2, round, then divide by 2???

more ▼

answered Aug 05 '11 at 04:12 PM

Graham Dunnett gravatar image

Graham Dunnett ♦♦
11.7k 11 20 64

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x211
x97
x23

asked: Aug 05 '11 at 04:02 PM

Seen: 11620 times

Last Updated: Aug 05 '11 at 09:22 PM