c#除法中小数点的问题

在c#中除法默认不保留小数点,看看下面的结果

decimal result = 100 / 1000; // result = 0;

需要保留小数点,可以如下

decimal result = 100m / 1000;

m代表decimal.

如果是变量要如何处理呢?这是需要用到Math.Round()

int x= 120;

int y= 100000;

decimal result = (decimal)x / y; // (decimal)x/ y 表示把 x 转换成decimal再做除法运算,int 除 int 是会丢失小数点的。

不过这样的小数点后面的数太多了,需要处理下,这时候需要Math.Round()

decimal result = Math.Round((decimal)x/ y,2);

后面的2表示保留小数点后2位小数.这样ok啦:)

 

 

posted @ 2008-10-31 16:44  IT高薪猎头  阅读(8821)  评论(2编辑  收藏  举报