多种做法比较
class Program_保留两位小数但不四舍五入
{
static void Main(string[] args)
{
Helper.Run(delegate ()
{
method1();
}, 1000000, " 1.先乘后除,再强制类型转换 ");
Helper.Run(delegate ()
{
method2();
}, 1000000, " 2.使用substring截取字符串,然后转换 ");
Helper.Run(delegate ()
{
method4();
}, 1000000, " 4.使用math.floor ");
Helper.Run(delegate ()
{
method5();
}, 1000000, " 5.使用正则来处理字符串数据,然后再类型转换 ");
Console.ReadKey();
}
const double num = 15.1257;
static void method1()
{
var tmp = (int)(num * 100) / 100.00;
}
static void method2()
{
var str = (num).ToString();
var tmp = double.Parse(str.Substring(0, str.IndexOf('.') + 3));
}
//static void method3()
//{
// var tmp = double.Parse((num).ToString("#0.00"));
//}
static void method4()
{
var tmp = Math.Floor(num * 100) / 100.00;
}
static void method5()
{
var tmp = double.Parse(Regex.Match(num.ToString(), @"[\d]+.[\d]{0,2}").Value);
}
//结果:method1 最快,而使用系统的方法或者字符串截取的方法都会慢一些
}
帮助类
public static class Helper
{
public static void Run(Action action, int stepTotal = 10000, string description = "")
{
DateTime startTime = DateTime.Now;
for (int i = 0; i < stepTotal; i++)
{
action();
}
DateTime endTime = DateTime.Now;
var ts = endTime - startTime;
Console.WriteLine(description + "_运行“" + stepTotal.ToString() + "”次耗时:" + (endTime - startTime).TotalMilliseconds.ToString() + "ms");
}
}