[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 335
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

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