C# 保留文字和小数,四舍五入,中国式四舍五入,上取整,下取整

本文详细介绍了使用C#进行数值处理的各种方法,包括保留小数、四舍五入、上取整、下取整和保留特定位数的小数。特别强调了如何在不同场景下选择合适的数值处理方式,如在财务计算、分页算法和显示数据时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.保留一位小数(文本加数字)

  string str = "余额为1000.236万元";
  Regex r = new Regex("\\d+\\.?\\d*");
  string result = string.Empty;
  if (r.IsMatch(str))
     {
            MatchCollection mc = r.Matches(str);
            string temp = mc.Count > 0 ? mc[0].ToString() : "";
            string show = Math.Round(Convert.ToDecimal(temp), 1, MidpointRounding.AwayFromZero).ToString();
            Console.WriteLine(show);
             result = Regex.Replace(str, "\\d+\\.?\\d*", show);
        }
    else
        {
              result = str;
          }                    
     Console.WriteLine(result);

2.四舍五入(纯数字)

Math.Round(0.0) //0
Math.Round(0.1) //0
Math.Round(0.2) //0
Math.Round(0.3) //0
Math.Round(0.4) //0
Math.Round(0.5) //0
Math.Round(0.6) //1
Math.Round(0.7) //1
Math.Round(0.8) //1
Math.Round(0.9) //1
说明:对于1.5,因要返回偶数,所以结果为2

C#中的Math.Round()并不是使用的"四舍五入"法。其实在VB、VBScript、C#、J#、T-SQL中Round函数都是采用Banker's rounding(银行家算法),即:四舍六入五取偶。事实上这也是IEEE的规范,因此所有符合IEEE标准的语言都应该采用这样的算法。

对于中国式取整:

.NET 2.0 开始,Math.Round 方法提供了一个枚举选项 MidpointRounding.AwayFromZero 可以用来实现传统意义上的"四舍五入"。即:

 Math.Round(4.5, MidpointRounding.AwayFromZero) = 5。

3.上取整(纯数字)

Math.Ceiling(0.0) //0
Math.Ceiling(0.1) //1
Math.Ceiling(0.2) //1
Math.Ceiling(0.3) //1
Math.Ceiling(0.4) //1
Math.Ceiling(0.5) //1
Math.Ceiling(0.6) //1
Math.Ceiling(0.7) //1
Math.Ceiling(0.8) //1
Math.Ceiling(0.9) //1

说明:例如在分页算法中计算分页数很有用。

4.下取整(纯数字)

Math.Floor(0.0) //0
Math.Floor(0.1) //0
Math.Floor(0.2) //0
Math.Floor(0.3) //0
Math.Floor(0.4) //0
Math.Floor(0.5) //0
Math.Floor(0.6) //0
Math.Floor(0.7) //0
Math.Floor(0.8) //0
Math.Floor(0.9) //0


5.保留小数(纯数字)


保留1位:
static void method1(double num)
{
var tmp = (int)(num * 10) / 10.00;
}
保留2位:
static void method2(double num)
{
var tmp = (int)(num * 100) / 100.00;
}
保留3位:
static void method2(double num)
{
var tmp = (int)(num * 1000) / 1000.00;
}

注:1取自https://www.cnblogs.com/studyh5/p/9819677.html

2 3 4 5 取自https://www.cnblogs.com/dianli_jingjing/p/7065122.html  &  https://www.cnblogs.com/lonelyxmas/p/5203494.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值