Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

This has really stumped me as I'm not exactly sure how I can acheive it.

I have the number 4999 and I wish to round down to the nearest value ending in 2, so in this case 4999 should return 4992. Is anyone able to help me with this?

Regards,
suprsnipes
Posted
Comments
Sampath Lokuge 10-Aug-13 7:44am    
Can you explain your use case or business scenario for required this kind of weird solution?
Mehdi Gholam 10-Aug-13 8:10am    
The nearest value is 5002 not 4992.
ridoy 10-Aug-13 8:46am    
OP said nearest down,so it should be 4992 i think.
Mehdi Gholam 10-Aug-13 8:52am    
I missed the round down part :)

You can do this by :
C#
int value = 4999;
int v = (value/10)*10 +2;
 
Share this answer
 
Comments
ridoy 10-Aug-13 8:48am    
i think this should be the solution,excellent,+5.
Mehdi Gholam 10-Aug-13 12:40pm    
Thanks ridoy!
Thanks7872 10-Aug-13 9:51am    
Nice shot..!!!! upvoted..!
Mehdi Gholam 10-Aug-13 12:41pm    
Thanks Rohan!
Manas Bhardwaj 10-Aug-13 12:33pm    
Yes +5!
C#
int a=4999;// getting the user input
int b = a, c = a;// defining two variables 'b' is for finding nearest number bigger than user input and 'c' is for finding nearest number smaller than user input
int i, j;
// a for loop to finding nearest bigger number and keep it in 'b'
for (i = 0; ; i++)
  if (byte.Parse(b.ToString().Substring(b.ToString().Length - 1)) == 2)
      break;
  else
      b++;
// a for loop to finding nearest smaller number and keep it on 'c'
for (j = 0; ; j++)
  if (byte.Parse(c.ToString().Substring(c.ToString().Length - 1)) == 2)
      break;
  else
      c--;
//compare to nearest number that had been found and find wich one is more near to input number
if (i >= j)
  MessageBox.Show(c.ToString());
else
  MessageBox.Show(b.ToString());

If you need find just nearest smaller number use this one:
C#
int a=4999;
int c = a;
int j;
for (j = 0; ; j++)
    if (byte.Parse(c.ToString().Substring(c.ToString().Length - 1)) == 2)
        break;
    else
        c--;
MessageBox.Show( c.ToString());
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900