5

I want to The numbers are being rounded to the nearest 10's place. For example, a number like 17.3 is being rounded to 20.0. and want to be allow three significant digits. Meaning for round to the nearest tenth of a percent as the last step of the process.

Sample :

    the number is 17.3 ,i want round to 20 ,

    and this number is 13.3 , i want round to 10 ?

How can i do this ?

5 Answers5

7

Chris Charabaruk gives you your desired answer here

To get to the core, here is his solution as an extension method:

public static class ExtensionMethods
{
    public static int RoundOff (this int i)
    {
        return ((int)Math.Round(i / 10.0)) * 10;
    }
}

int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10

//edit: This method only works for int values. You'd have to edit this method to your liking. f.e.: public static class ExtensionMethods

{
    public static double RoundOff (this double i)
    {
       return (Math.Round(i / 10.0)) * 10;
    }
}

/edit2: As corak stated you should/could use

Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10
Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
  • 1
    Is the cast to `double` really necessary? And to avoid bankers rounding shenanigans, I'd use `Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10` – Corak Aug 21 '13 at 06:19
2

Other answers are correct also, but here's how you'd do it without Math.Round:

((int)((17.3 + 5) / 10)) * 10 // = 20
((int)((13.3 + 5) / 10)) * 10 // = 10
((int)((15.0 + 5) / 10)) * 10 // = 20
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • What specific reason do you have for doing it without `Round`? Are you assuming you're doing it more efficiently than the math library is? – arkon Oct 17 '22 at 09:43
0

Try this-

double d1 = 17.3;
int rounded1 = ((int)Math.Round(d/10.0)) * 10; // Output is 20

double d2 = 13.3;
int rounded2 = ((int)Math.Round(d/10.0)) * 10; // Output is 10
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
0
double Num = 16.6;
int intRoundNum = (Convert.ToInt32(Math.Round(Num / 10)) * 10);
Console.WriteLine(intRoundNum);
Prabhakaran Parthipan
  • 4,193
  • 2
  • 18
  • 27
0

If you want to avoid casting or pulling in the math library you could also use the modulus operator and do something like the following:

int result = number - (number % 10);
if (number % 10 >= 5)
{
    result += 10;
}

For your given numbers:

number processing result
13.3 13.3 - (3.3) 10
17.3 17.3 - (7.3) + 10 20
Andrew Cameron
  • 73
  • 1
  • 12