如何使用C#舍入两个十进制数字 [英] how to round up two decimal numbers using c#

查看:106
本文介绍了如何使用C#舍入两个十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我将两个小数点四舍五入,

到目前为止我尝试过的地方:

Hi guys,

I was rounding up the two decimal numbers,

where i tried so far:

int amt = Convert.ToInt32(Math.Round((conc * vol) / 1000, 2));
txtamt.Text = amt.ToString();



但是,如果数字为2.5,则仅给出结果2,但
我正在寻找3

谁能帮助我.

谢谢



but, if the number is 2.5,it is giving only result as 2, but
i''m looking for 3

Can any one plzzz help me.

thanks

推荐答案

这就是为什么这样:Math.Round((conc * vol) / 1000, 2)返回2.5,但是Convert.ToInt32不会四舍五入,它只是在截断后截取一部分小数点.

如果只需要3,则不必四舍五入到小数点后两位,只需执行以下操作:
This is why it is happening: Math.Round((conc * vol) / 1000, 2) returns 2.5, but Convert.ToInt32 doesn''t round it, it just truncates the part after the decimal point.

If you just want 3, then it''s not necessary to round to two decimal places, just do this:
int amt = (int)Math.Round((conc * vol) / 1000, MidpointRounding.AwayFromZero);


MidpointRounding.AwayFromZero确保输入的是2.5,例如,得到3.


The MidpointRounding.AwayFromZero makes sure that you get, for example, 3 if the input is 2.5.


感谢上帝,我明白了.

Thank God, i got it,.

double amt = Convert.ToDouble(Math.Round(((conc * vol) / 1000), 2));
                decimal i = decimal.Round(Convert.ToDecimal(amt), MidpointRounding.AwayFromZero);
                txtamt.Text = i.ToString();


这篇关于如何使用C#舍入两个十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆