C# Decimal四舍五入到指定小数位数

一、实现

在实现Excel导出时,导出列要求使用数值类型,不能通过ToString将原有的decimal先格式化后再导出,

有两种实现方法,以保留两位小数为例

方式一:

decimal temp=232.23234234;
int decision=2;
int calc = (int)Math.Pow(10, decision);
temp = Math.Round(temp * calc) / calc;

方式二:

decimal temp=232.23234234;
int decision=2;
temp = System.Decimal.Round(temp, decision);

二、 其它:

Java中

Math类提供了3个有关取整的方法:ceil()、floor()、round()。

这些方法与他们的英文名字相对应:

1、ceil,天花板,意思就是向上取整,Math.ceil(11.5)的结果为12,Math.ceil(-11.5)的结果为-11。

2、floor,地板,意思就是向下取整,Math.floor(11.5)的结果为11,Math.floor(-11.5)的结果为-12。

3、round,表示四舍五入,算法为:Math.floor(x+0.5),即将原来的数字加上0.5后在向下取整,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。

C#中

1、Math.Round是"就近舍入",当要舍入的是5时与"四舍五入"不同(取偶数),如:
Math.Round(0.5,0)=0    
Math.Round(1.5,0)=2    
Math.Round(2.5,0)=2    
Math.Round(3.5,0)=4 

2、Math.Truncate 计算双精度浮点数的整数部分,即直接取整数,如:
Math.Truncate(-123.55)=-123, 
Math.Truncate(123.55)=123   

3、Math.Ceiling 取天板值,即向上取整,与"四舍五入"无关。
Math.Ceiling(1) = 1
Math.Ceiling(1.1) = 2
Math.Ceiling(1.5) = 2
Math.Ceiling(3.1) = 4 

4、Math.Floor 取地板值,即向下取整,与"四舍五入"无关。
Math.Floor(1) = 1
Math.Floor(1.1) = 1
Math.Floor(1.5) = 1
Math.Floor(3.9) = 3