uncategorized

C# 無條件進位,無條件捨去及四捨五入寫法

雖然程式很簡單,但是,一時要用還真的不知道要怎樣寫,畢竟現在一個程式開發者要記憶的東西太多,所以,不時時刻刻記憶一些東西還真的不行呢

無條件進位


1
2
3
double s = 100;
int result = 0;
result = Convert.ToInt16(Math.Ceiling(s / 3));

無條件捨去


1
2
3
double s = 100;
int result = 0;
result =Convert.ToInt16( Math.Floor(s / 3));

四捨五入


使用Math.Round, Math.Round(計算值,小數點第幾位)

1
2
3
double s = 110;
double result = 0;
result = Math.Round((s / 3), 2);

若是要呈現一般認知的四捨五入需加入第三個參數,MidpointRounding.AwayFromZer

1
System.Math.Round(1.235 , 2, MidpointRounding.AwayFromZero)


參考來源:http://msdn.microsoft.com/zh-tw/library/ef48waz8(v=VS.100).aspx