tags:

views:

84

answers:

2

Hi.

Consider the following C# code:

Decimal number = new decimal(8.0549);
Decimal rounded = Math.Round(number, 2);
Console.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.

+1  A: 

No; you'll need to write it yourself.

SLaks
+1  A: 

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));
Bob Palmer
Just don't do this, otherwise at the end of the routine, things will be unleashed and children will be eaten.
Bob Palmer
@Bob Palmer... indeed ... but to come up with this on Halloween is highly appropriate though:-)
Steve Haigh
Shouldn't `i` decrease instead of increasing?
Maciej Hehl
You're right - fixed the code
Bob Palmer