多種做法比較
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");
}
}
