close

同步發表於Google Blogger

C# 除法顯示小數點

decimal result = 100 / 1000; // result = 0;
需要保留小數點,可以如下
decimal result = 100m / 1000;
m代表decimal.
如果是變量要如何處理呢?這是需要用到Math.Round()
int x= 120;
int y= 100000;
decimal result = (decimal)x / y; // (decimal)x/ y 表示把 x 轉換成decimal再做除法運算,int 除 int 是會丟失小數點的。
不過這樣的小數點後面的數太多了,需要處理下,這時候需要Math.Round()
decimal result = Math.Round((decimal)x/ y,2);
後面的2表示保留小數點後2位小數.這樣ok啦:)

arrow
arrow
    全站熱搜

    createps 發表在 痞客邦 留言(0) 人氣()