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

女生的网名这么多〃 提交于 2019-12-10 02:26:40

问题


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;
}

回答1:


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);



回答2:


Use Math.Floor if you want to round down tha value, or Math.Round if you want to get an exact round. Math.Truncate simply remove the decimal part of the number,so you get bad results for negative numbers:

var result= Math.Floor(number * 100) / 100;

Math.Floor always return the smallest integral value that is lesser (Floor ) or greater (Ceiling) than the specified value. So you don't get a correct rounding. Example:

Math.Floor(1.127 * 100) / 100 == 1.12 //should be 1.13 for an exact round
Math.Ceiling(1.121 * 100) / 100 == 1.13 //should be 1.12 for an exact round

Always prefer the version of Math.Round containing the mid-point rounding param. This param specify how to handle mid-point values (5) as last digit.

If you don't specify AwayFromZero as the value for param, you'll get the default behaviour, which is ToEven. For example, using ToEven as rounding method, you get:

Math.Round(2.025,2)==2.02 
Math.Round(2.035,2)==2.04

instead, using MidPoint.AwayFromZero param:

Math.Round(2.025,2,MidpointRounding.AwayFromZero)==2.03
Math.Round(2.035,2,MidpointRounding.AwayFromZero)==2.04

So, for a normal rounding, it's best to use this code:

var value=2.346;
var result = Math.Round(value, 2, MidpointRounding.AwayFromZero);



回答3:


Use .Truncate() to get exact amount, or .Round() to round off.

decimal dNum = (decimal)165.6598F;
decimal dTruncated = (decimal)(Math.Truncate((double)dNum*100.0) / 100.0); //Will give 165.65
decimal dRounded = (decimal)(Math.Round((double)dNum, 2)); //Will give 165.66

Or you can make an extension method to run it like dNum.ToTwoDecimalPlaces();

public static class Extensions
{ 
    public static decimal ToTwoDecimalPlaces(this decimal dNum)
    {
        return ((decimal)(Math.Truncate((double)dNum*100.0) / 100.0));
    }
}



回答4:


Math.Floor(number * 100) / 100;



回答5:


There is no build in method in the .net framework to do this, other answers say how to write your own code.



来源:https://stackoverflow.com/questions/3797342/how-do-i-round-down-a-decimal-to-2-decimal-places-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!