在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啦:)

 

 

相关文章:

  • 2022-12-23
  • 2021-09-09
  • 2021-05-26
  • 2023-03-20
  • 2021-12-18
  • 2022-03-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
  • 2021-11-06
相关资源
相似解决方案