Rounding a number using non standard rules
Consider the following C# code:
Decimal number = new decimal(8.0549);
Decimal rounded = Math.Round(number, 2);
Cons开发者_如何学运维ole.WriteLine("rounded value: {0}", rounded);
will produce the output: 8.05
Math.Round's algoritm only checks the next digit beyond the decimals number taken as parameter.
I need a algoritm that checks all the decimals chain. In this case, 9 should rounds 4 to 5 which in turn will rounds 5 to 6, producing the final result 8.06More exemples:
8.0545 -> 8.06 8.0544 -> 8.05There's some built-in method that can help me?
Thanks.No; you'll need to write it yourself.
I would expect that if there were a built in method to do this, it would have already been reported as a bug ;)
That being said - you could create a method that takes your decimal, along with the max and min number of places to round in reverse from, and in a loop crush it down to the desired places - i.e. something like this:
private static double NotQuiteRounding(double numToRound, int maxPlaces, int minPlaces)
{
int i = maxPlaces;
do
{
numToRound = Math.Round(numToRound,i);
i = i - 1;
}
while (i >= minPlaces);
return numToRound;
}
And call it like this:
Console.WriteLine(NotQuiteRounding(8.0545,10,2));
Console.WriteLine(NotQuiteRounding(8.0544,10,2));
精彩评论