Igor
Igor

Reputation: 6255

Math.Round with negative parameter

ALL,

I am trying to convert Borland C++ code to C#. In the old code I see the following:

double a = RoundTo( b, -2 );

Looking at Borland documentation I see that RoundTo() accept both positive and negative parameters for precision. Positive means round to 10^n, negative - to 10^-n.

Looking at the C# documentation of Math.RoundTo() I can't find a reference whether it will accept negative numbers for precision. And all samples are presented with the positive numbers.

What is the proper way of converting the code in this case? Should I just forget about the sign and write:

double a = Math.Round( b, 2 );

Thank you.

Upvotes: 8

Views: 7889

Answers (3)

Adam Gritt
Adam Gritt

Reputation: 2674

I am not aware of a built in solution to the type of rounding you are looking to do but that doesn't mean there isn't one somewhere. A quick solution would be to create a method or even an extension method to do what you are looking for:

double DoubleRound(double value, int digits)
{
    if (digits >= 0)
    {
        return Math.Round(value, digits);
    }
    else
    {
        digits = Math.Abs(digits);
        double temp = value / Math.Pow(10, digits);
        temp = Math.Round(temp, 0);
        return temp * Math.Pow(10, digits);
    }
}

Upvotes: 6

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

Math.Round for doubles in C# cannot accept negative values for digits (in fact it's documented in that very page to throw an ArgumentOutOfRangeException if digits is less than 0 or greater than 15)

The parameter is in the case of Math.Round instead asking for a certain number of fractional digits which means the sign of the parameter would be reversed, so in your case, yes,

double a = Math.Round( b, 2 );

would be a correct translation of RoundTo with a -2 parameter.

Upvotes: 5

001
001

Reputation: 13533

Did you try it? I did and got an exception:

System.ArgumentOutOfRangeException: Rounding digits must be between 0 and 15, inclusive.
Parameter name: digits 
   at System.Math.Round(Double value, Int32 digits)
   at MyClass.RunSnippet()
   at MyClass.Main()

Upvotes: 2

Related Questions