• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 340
  • Last Modified:

C# rounding function


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
lblinc
Asked:
lblinc
3 Solutions
 
2266180Commented:
well .. I guess the following mathematical algorithm should work just fine:

Math.Ceiling((x*100))/100
0
 
GENTPCommented:
Math.Round(x,2);

This will round to the second decimal place.
0
 
2266180Commented:
but for the first example, that will get: 93.54 no?
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
aaronfengCommented:
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
 
MyersACommented:
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
 
MyersACommented:
I forgot the rounding :

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

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

Vaughn
0
 
MyersACommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now