在c#中将数字舍入为零



在我的数据库中,我有三个点浮点数列和一个将前两个列相乘以获得第三个值

的进程item.ValorTotal = Math.Round(item.Qtde * item.ValorUnitario, 2, MidpointRounding.AwayFromZero);

但如果我的项目。Qtde是0.03,我的物品。ValorUnitario是0.02,item。ValorTotal结果是0.0006,变量因为四舍五入而接收到零,我怎样才能四舍五入得到0.01,并继续使用小数点后的两个数字?

简而言之,当我收到0.006或0.0006等较低的数字时,我确实喜欢四舍五入到第一个可能的数字(0.01)

可以用Math.Ceiling()代替Math.Round()

C#中的Math.Ceiling()方法用于返回大于或等于指定数的最小整数值。

那么在你的代码示例中,它将是这样的:

item.ValorTotal = (Math.Ceiling((item.Qtde * item.ValorUnitario) * 100) / 100);

输出:

0,0006 => 0,01
0,0106 => 0,02

AwayFromZero并不意味着你总是向上舍入。实际上,它像通常的四舍五入一样适用于大多数值。据我所知,只有将0.005x取整才会产生效果。因此写

item.ValorTotal = Math.Round(item.Qtde * item.ValorUnitario + 0.005, 2, MidpointRounding.AwayFromZero);

当你想向上舍入并且两个值都是正数时。

最新更新