Welcome to MSDN Blogs Sign in | Join | Help

Kathy Kam

Reflection on the CLR and .NET
Rounding Up

Since my last post, some people asked me "Well.. great... how do I round up?" Particularly since SQL doesn't do the same rounding as the CLR. SQL's default (and only) rounding algorithm is Rounding Up.

i.e.
SELECT ROUND(2.45, 2), ROUND(2.45, 1)
GO
SELECT ROUND(3.45, 2), ROUND(3.45, 1)
GO
SELECT ROUND(-2.45, 2), ROUND(-2.45, 1)
GO
SELECT ROUND(-3.45, 2), ROUND(-3.45, 1)
GO

Returns:
------- -------
2.45 2.50
3.45 3.50
-2.45 -2.4
-3.45 -3.4


In order to achieve the same rounding as SQL from .NET, you can simply write something like this:

    public static double MathRoundUp(double d, int decimals) 
    { 
        if (d < 0) 
        { 
            double pow = Math.Pow(10, (decimals + 2) * -1); 
            d += pow; 
        } 
        d = Math.Round(d, decimals, MidpointRounding.AwayFromZero); 
        return d; 
    }
If you have a better algorithm, send it to me!
Posted: Tuesday, March 07, 2006 5:40 PM by KathyKam
Filed under:

Comments

Jason Haley said:

# March 12, 2006 7:08 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker