Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round down a decimal to 2 decimal places in .Net?

This should be easy, but I can’t find a built in method for it, the .net framework must have a method to do this!

private decimal RoundDownTo2DecimalPlaces(decimal input)
{
   if (input < 0)
   {
      throw new Exception("not tested with negitive numbers");
   }

   // There must be a better way!
   return Math.Truncate(input * 100) / 100;
}
like image 545
Ian Ringrose Avatar asked Sep 26 '10 10:09

Ian Ringrose


People also ask

How do you round a number to two decimal places in asp net?

Round(temp, 2);

How do you round off decimals in C#?

Round(Decimal) Method. This method is used to round a decimal value to the nearest integer. Syntax: public static decimal Round (decimal d); Here, it takes a decimal number to round.


2 Answers

Math.Floor(number * 100) / 100;
like image 171
Itay Karo Avatar answered Oct 07 '22 14:10

Itay Karo


If you are rounding down then you need:

Math.Floor(number * 100) / 100;

if you are looking for something called 'bankers rounding' (probably not if it's for output and not for statistics/summing) then:

Math.Round(number, 2);

Finally if you want, not sure what the correct term is, 'normal rounding':

Math.Round(number, 2, MidpointRounding.AwayFromZero);
like image 24
FinnNk Avatar answered Oct 07 '22 15:10

FinnNk