提问者:小点点

四舍五入在c sharp中不像预期的那样工作


舍入未按预期工作:

对于这个值403.1245,我期望四舍五入后的结果为403.13。

我尝试过这个逻辑,但没有找到这个值:403.13

Math.Round(403.125);

403

Math.Round(403.125,2)

403.12

Math.Round(403.135,2)

403.14

Math.Round(403.145,2)

403.14

Math.Round(403.115,2)

403.12

Math.Round(403.125,2,midpointrounding.toeven)

403.12

Math.Round(403.125,2,midpointrounding.awayfromzero)

403.13

Math.Round(403.115,2,midpointrounding.awayfromzero)

403.12

Math.Round(403.114,2,midpointrounding.awayfromzero)

403.11

Math.Round(403.1145,2,midpointrounding.awayfromzero)

403.11

Math.Round(403.1145,3,midpointrounding.awayfromzero)

403.115

Math.Round(403.1145,2,midpointrounding.awayfromzero)

403.11

403.115.ToString(“0.00”)

“403.12”

403.1145.ToString(“0.00”)

“403.11”

403.1145.ToString(“0.000”)

“403.115”

403.1145.ToString(“0.01”)

“403.11”

403.1245.ToString(“0.01”)

“403.11”

string str=string.Format(“{0:0.00}”,403.1245M);

字符串

“403.12”


共3个答案

匿名用户

您可以在。NET Core中使用它

Math.Round(403.1245, 2, MidpointRounding.ToPositiveInfinity);

结果:403.13

匿名用户

在。NET Framework 4.7.2中使用默认的Math.Round()方法是不可能达到预期值的,必须为此编写自定义扩展方法。

Math.Round提供了以下方法。

double d = Math.Round(403.1245, 3, MidpointRounding.AwayFromZero); //403.125
double d = Math.Round(403.1245, 3); //403.124

但是在。NET Core3中,您可以得到这个。

double d = Math.Round(403.1245, 2, MidpointRounding.ToPositiveInfinity);

匿名用户

我认为您在。NET Framework上需要以下内容:

Math.Round(Math.Round(403.1245, 3, MidpointRounding.AwayFromZero), 2, MidpointRounding.AwayFromZero)

我也不是很清楚你是想解决一些奇怪的边情况,还是想让“m.noxx形式的每个数字都四舍五入到m.n(o+1)”--在这种情况下,你可能需要自己四舍五入,可能乘以100,四舍五入(就像Math.ceil),再除以100等等