问题
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 ?
回答1:
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
回答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
回答3:
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
回答4:
double Num = 16.6;
int intRoundNum = (Convert.ToInt32(Math.Round(Num / 10)) * 10);
Console.WriteLine(intRoundNum);
来源:https://stackoverflow.com/questions/18349844/rounded-to-the-nearest-10s-place-in-c-sharp