C#四舍五入、上取整、下取整


四舍五入:

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。

 

上取整:

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

說明:例如在分頁算法中計算分頁數很有用。

 

下取整 :

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

 

保留小數,不四舍五入


保留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;
}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM