简体   繁体   English

将 double 舍入到特定的十进制值

[英]Round double to specific decimal value

How can I round a double to the next.95?我如何将双精度舍入到 next.95?

Here's what I want to achieve:这是我想要实现的目标:

4.15 should become 4.95
5.95 should become 5.95
6.96 should become 7.95

How can I achieve this?我怎样才能做到这一点?

I tried using Math.Round(), but it seems like it only supports rounding to a specific amount of decimal points.我尝试使用 Math.Round(),但它似乎只支持舍入到特定数量的小数点。 Not a specific value.不是一个特定的值。 I also tried this solution , but it seems like this only works for whole numbers.我也试过这个解决方案,但似乎这只适用于整数。

here's what I thought:这就是我的想法:

public static decimal myMethod(decimal inp)
{
    decimal flr = Math.Ceiling(inp) - 0.05m;
    decimal cll = Math.Ceiling(inp) + 1m - 0.05m;
    
    return flr >= inp ? flr : cll;
}

you probably need to make some tests though, as I only tested your values不过,您可能需要进行一些测试,因为我只测试了您的值

There is no out-of-the-box function available, so you've to implement your own logic.没有开箱即用的 function 可用,因此您必须实现自己的逻辑。

A first approach could try to follow "human logic" and look like this:第一种方法可以尝试遵循“人类逻辑”,如下所示:

var result = (input - Math.Floor(input)) > .95
                    ? Math.Ceiling(input) + .95
                    : Math.Floor(input) + .95;

As we can see, we have to calculate the result twice, so I guess the following approach should be faster (while it really shouldn't matter and we should add a real benchmark if it matters).正如我们所看到的,我们必须计算两次结果,所以我猜下面的方法应该更快(虽然它真的不应该重要,如果重要的话我们应该添加一个真正的基准)。

var candidate = Math.Floor(input) + .95;
var result = candidate < input ? candidate + 1 : candidate;

It gets easier if you shift the origin: Instead of rounding a number x up to the next 0.95 you can increment it by 0.05, then round up to the next integer and finally subtract the 0.05 again:如果你改变原点,它会变得更容易:你可以将它增加 0.05,而不是将数字 x 向上舍入到下一个 0.95,然后向上舍入到下一个 integer,最后再次减去 0.05:

Math.Ceiling(x + 0.05m) - 0.05m Math.Ceiling(x + 0.05m) - 0.05m

No need for any case distinctions.不需要任何大小写区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM