内置的.Net算法一轮价值到最近的10间隔 [英] Built in .Net algorithm to round value to the nearest 10 interval

查看:92
本文介绍了内置的.Net算法一轮价值到最近的10间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#圆钢任意值10间隔?举例来说,如果我有11,我想它返回10,如果我有136的话,我想它返回140

How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140.

我可以很容易地用手工做的。

I can easily do it by hand

return ((int)(number / 10)) * 10;

但我在寻找一种内建算法来做好这项工作,像Math.Round()。为什么我不想用手工做的原因是,我不想写相同或相似的一块code的都在我的项目,即使是上述简单的东西。

But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above.

推荐答案

有在类库,将做到这没有内置的功能。最接近的是 System.Math.Round()这是唯一的数字四舍五入类型十进制和双到最近的整数值。但是,你可以用你的声明了一个扩展方法,如果您正在使用.NET 3.5,这将让你更清晰地使用此功能工作。

There is no built-in function in the class library that will do this. The closest is System.Math.Round() which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.

public static class ExtensionMethods
{
    public static int RoundOff (this int i)
    {
        return ((int)Math.Round(i / 10.0)) * 10;
    }
}

int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10

如果你是编程针对的是旧版本的.NET Framework,只是删除了本,从舍入函数,调用该函数像这样:

If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so:

int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240
int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10

这篇关于内置的.Net算法一轮价值到最近的10间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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