开发者

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.06

More exemples:

8.0545 -> 8.06

8.0544 -> 8.05

There'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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜