四舍五入到C#中最接近的10位数 [英] rounded to the nearest 10's place in c#

查看:86
本文介绍了四舍五入到C#中最接近的10位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字四舍五入到最近的 10 位置.例如,像 17.3 这样的数字将四舍五入为 20.0 .并希望允许使用三个有效数字.舍入到最接近百分之一的百分比作为该过程的最后一步.

I want to The numbers are being rounded to the nearest 10's place. For example, a number like 17.3 is being rounded to 20.0. and want to be allow three significant digits. Meaning for round to the nearest tenth of a percent as the last step of the process.

样本:

    the number is 17.3 ,i want round to 20 ,

    and this number is 13.3 , i want round to 10 ?

我该怎么做?

推荐答案

Chris Charabaruk为您提供所需的答案

Chris Charabaruk gives you your desired answer here

要进入核心,这是他作为扩展方法的解决方案:

To get to the core, here is his solution as an extension method:

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

//此方法仅适用于int值.您必须根据自己的喜好编辑此方法.f.e .:公共静态类ExtensionMethods

//edit: This method only works for int values. You'd have to edit this method to your liking. f.e.: public static class ExtensionMethods

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

/edit2:如corak所述,您应该/可以使用

/edit2: As corak stated you should/could use

Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10

这篇关于四舍五入到C#中最接近的10位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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