user1423745
user1423745

Reputation: 51

How do I round to the nearest 0.5 with following sequense

I have to display ratings and for that i need increments as follows:

If the number is 1.0 it should be equal to 1

If the number is 1.1 should be equal to 1

If the number is 1.2 should be equal to 1.5

If the number is 1.3 should be equal to 1.5

If the number is 1.4 should be equal to 1.5

If the number is 1.5 should be equal to 1.5

If the number is 1.6 should be equal to 1.5

If the number is 1.7 should be equal to 1.5

If the number is 1.8 should be equal to 2.0

If the number is 1.9 should be equal to 2.0

If the number is 2.0 should be equal to 2.0

If the number is 2.1 should be equal to 2.0

and so on...

Is there a simple way to compute the required values?

Upvotes: 0

Views: 114

Answers (4)

Andy
Andy

Reputation: 3743

Try this:

r = Math.Floor(v) + 0.5*( 
                        Math.Floor(v + 0.8) - Math.Floor(v) 
                      + Math.Floor(v + 0.2) - Math.Floor(v) )

This can be simplified as:

r = 0.5 * ( Math.Floor(v + 0.8) + Math.Floor(v + 0.2) )

Upvotes: 0

Carra
Carra

Reputation: 17964

double nr = 15.9;
double rounded = (int)nr;
double rest = Math.Round(nr - rounded, 5);
if(0.2 <= rest && rest <= 0.7)
  rounded += 0.5;
else if (0.7 < rest)
  rounded += 1;

Tested with 15.0 > 15.9. Seems to work OK.

Upvotes: 0

Code Uniquely
Code Uniquely

Reputation: 6373

Since 1.2 is nearer 1.0 than 1.5, your're not really rounding to nearest 0.5 and the standard Math.Round() function isn't really going to do the whole job for you.

You're going to need to shift the value slightly when there is a .2 in the sequence.

Try using this:

var shiftBy = ((int)Math.Round(v*10) % 10 == 2) ? 0.1 : 0;

var nearest = Math.Round((v + shiftBy)*2)/2.0;

Upvotes: 2

Hans Kesting
Hans Kesting

Reputation: 39284

One way would be this to round v:

v = Math.Round(v*2.0) / 2.0;

but this will round 1.2 down to 1.0. (It's a bit strange that both 1.2 and 1.7 should round to 1.5)

Upvotes: 1

Related Questions