Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round with negative parameter

Tags:

c++

c#

rounding

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.

like image 908
Igor Avatar asked Aug 20 '12 19:08

Igor


3 Answers

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);
    }
}
like image 94
Adam Gritt Avatar answered Oct 03 '22 00:10

Adam Gritt


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.

like image 38
Joachim Isaksson Avatar answered Oct 02 '22 23:10

Joachim Isaksson


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()
like image 44
Johnny Mopp Avatar answered Oct 02 '22 23:10

Johnny Mopp