Solved

# C#  rounding function

Posted on 2006-05-31
293 Views

Please refresh my memory on rounding in C#.    For example, if we have this number scenario:

93.5433

but we want this to be rounded UP every time to this:

93.5500

How to do that in C# ?

Thanks.

- - -  - - - -

Another example:

we have this:

34.7985

to be rounded UP to:

34.8000
0
Question by:lblinc

LVL 28

Assisted Solution

well .. I guess the following mathematical algorithm should work just fine:

Math.Ceiling((x*100))/100
0

LVL 5

Expert Comment

Math.Round(x,2);

This will round to the second decimal place.
0

LVL 28

Expert Comment

but for the first example, that will get: 93.54 no?
0

LVL 5

Assisted Solution

Or you could try Decimal.Round(x, 2);  This is same as GENTP.  Up to you which one you want to use.  Sometimes it's useful to use Decimal.Round because it's easier to tell what type of number you are rounding.

Cheers,

Aaron
http://aaronfeng.blogspot.com/
0

LVL 2

Expert Comment

Hi  lblinc,

See if this works:

double val = 34.7900;
if( val > (Math.Round(val,2)))
{
val += .01;
}

I checked it with your two example values and it rounded correctly.

Vaughn
0

LVL 2

Expert Comment

I forgot the rounding :

double val = 93.5433;
if( val > (Math.Round(val,2)))
{
val += .01;
}

Math.Round(val, 2)  //forgot this

Vaughn
0

LVL 2

Accepted Solution

geez... I forgot the ';' at the end:

double val = 93.5433;
if( val > (Math.Round(val,2)))
{
val += .01;
}
MessageBox.Show(Math.Round(val, 2).ToString());

Vaughn
0

## Featured Post

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…