Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...