C# 如何将十进制值四舍五入到最接近的 0.05 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1448458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:37:33  来源:igfitidea点击:

How to round decimal value up to nearest 0.05 value?

c#.netalgorithmdecimalrounding

提问by Prashant Cholachagudda

Is there any way to round up decimal value to its nearest 0.05 value in .Net?

有没有办法将十进制值四舍五入到 .Net 中最接近的 0.05 值?

Ex:

前任:

7.125 -> 7.15

7.125 -> 7.15

6.66 -> 6.7

6.66 -> 6.7

If its now available can anyone provide me the algo?

如果它现在可用,有人可以为我提供算法吗?

采纳答案by Adam Bellaire

How about:

怎么样:

Math.Ceiling(myValue * 20) / 20

回答by pavium

Duplicated hereand herefor ruby and python. It shouldn't be too different.

在此处此处为 ruby​​ 和 python复制。应该不会相差太大。

回答by Fredou

Math..::.Round Method (Decimal, Int32, MidpointRounding)

Math..::.Round 方法(十进制、Int32、中点四舍五入)

Rounds a double-precision floating-point value to the specified number of fractional digits. A parameter specifies how to round the value if it is midway between two other numbers.

将双精度浮点值舍入到指定的小数位数。参数指定如果该值位于其他两个数字的中间,则如何舍入该值。

   Math.Round(1.489,2,MidpointRounding.AwayFromZero)

回答by Marc

Use this:

用这个:

Math.Round(mydecimal / 0.05m, 0) * 0.05m;

The same logic can be used in T-SQL:

在 T-SQL 中可以使用相同的逻辑:

ROUND(@mydecimal / 0.05, 0) * 0.05

I prefer this approach to the selected answersimply because you can directly see the precision used.

我更喜欢这种方法而不是选择的答案,因为您可以直接看到使用的精度。

回答by zvolkov

Something like this should work for any step, not just 0.05:

像这样的东西应该适用于任何步骤,而不仅仅是 0.05:

private decimal RoundUp (decimal value, decimal step)
{
    var multiplicand = Math.Ceiling (value / step);
    return step * multiplicand;
}