C# Math.Round Up [英] C# Math.Round Up

查看:60
本文介绍了C# Math.Round Up的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.

我有一个小数,我想把它四舍五入到 2 位小数,而不是通常的方式

I have a decimal and I want to round this at 2 decimals, not at the ordinary way but

0.2013559322033898305084745763

0.2013559322033898305084745763

预期结果:0.21

我该怎么做?

推荐答案

听起来您想要一个 Math.Ceiling 版本,但它需要一些小数位.你可以乘,使用Math.Ceiling,然后再除:

It sounds like you want a version of Math.Ceiling, but which takes a number of decimal places. You could just multiply, use Math.Ceiling, then divide again:

public static double CeilingWithPlaces(double input, int places)
{
    double scale = Math.Pow(10, places);
    double multiplied = input * scale;
    double ceiling = Math.Ceiling(multiplied);
    return ceiling / scale;
}

(如果您当然需要 2 个小数位,您可以像 Dennis_E 的回答那样硬编码 100 的比例.)

(If you only ever need 2 decimal places of course, you can hard-code the scale of 100, as Dennis_E's answer does.)

现在,关于此的两个警告:

Now, two caveats about this:

  • 很可能在某些情况下,我们正在执行多项操作这一事实对您不利.浮点数学可能会很奇怪,特别是对于浮点二进制.(哎呀,浮点二进制小数点的小数位"的想法已经有问题了.)
  • 那总是向上取整,即远离负无穷大.所以它会将 -0.201 舍入到 -0.20.如果您想从 0 舍入,您可能需要单独处理负值,例如与

  • There may very well be situations where the fact that we're performing multiple operations works against you. Floating point maths can be weird like that, particularly with floating binary point. (Heck, the idea of "decimal places" with floating binary point is already problematic.)
  • That will always round up, i.e. away from negative infinity. So it would round -0.201 to -0.20. If you want to round away from 0, you may need to handle negative values separately, e.g. with

if (input < 0)
{
    return -CeilingWithPlaces(-input, places);
}

这篇关于C# Math.Round Up的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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