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