2010-08-02 103 views
10

我有像float =(x/y)這樣的變量; 每當num給出像34.443那樣的結果時,我需要將結果四捨五入。 那麼如何在c#中做到這一點?如何四捨五入

回答

25

使用Math.Ceiling

返回最小的整數大於 或等於指定數量

注意這對雙打,所以如果你想有一個浮動(或整數)你需要投。

float num = (float)Math.Ceiling(x/y); 
+2

如果兩個'x'和'y'是整數,它們會被截斷。 – Zaz 2010-08-02 12:55:11

+0

@Josh:沒錯。我認爲OP已經有了漂浮,因爲結果是34.443,但絕對值得明確地說出來。 – Quartermeister 2010-08-02 12:56:51

+0

根據要求的天花板或地板... – 2010-08-02 13:16:54

2

使用Math.Ceiling如果您是否小於答案整數想要的整數比答案更多的,或Math.Floor

Math.Ceiling(3.46) = 4; 
Math.Floor(3.46) = 3; 

無論使用哪一個需要你的情況。

+0

+1不錯......... – 2012-01-20 12:00:15

5
float num = (x/y); 
float roundedValue = (float)Math.Round(num, 2); 

如果我們使用Math.Round函數,我們可以指定沒有地方來回合。

+0

'Math.Ceiling' - 「我需要圓** ...... **」 – Zaz 2010-08-02 14:25:06

1

,如果您需要2位小數,喲可以使用類似:

float roundedvalue = (float)Math.Ceiling(x*100/y) /100; 
float roundedvalue = (float)Math.Floor(x*100/y) /100;