2012-09-27 132 views
33

可能重複:
How do you round a number to two decimal places in C#?四捨五入變量到小數點後兩位C#

我感興趣的是如何將變量四捨五入到小數點後兩位。在下面的例子中,獎金通常是一個有四位小數的數字。有沒有辦法確保薪酬變量總是四捨五入到小數點後兩位?

 pay = 200 + bonus; 
     Console.WriteLine(pay); 
+0

谷歌搜索? http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c – eouw0o83hf

+0

作業標籤已過時 –

+0

首頁工作標籤?只是現在看到它,http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated?cb=1 – Habib

回答

72

使用Math.Round並指定小數位數。

Math.Round(pay,2); 

Math.Round Method (Double, Int32)

回合雙精度浮點值到小數位指定數量 。

Math.Round Method (Decimal, Int32)或者

舍一個十進制值的小數位指定次數。

+0

並確保你正在使用'float','double'或'decimal'類型,否則這將無法工作。 – Aidiakapi

+0

我正在使用雙精度型,但它仍然不適用於我。 –

+3

叫它'pay = Math.Round(pay,2);' – Habib

5
decimal pay = 1.994444M; 

Math.Round(pay , 2); 
1
Console.WriteLine(decimal.Round(pay,2)); 
4

可以四捨五入的結果,並使用string.Format設置這樣的精度:

decimal pay = 200.5555m; 
pay = Math.Round(pay + bonus, 2); 
string payAsString = string.Format("{0:0.00}", pay); 
+1

我懷疑你可以在第一行使用兩種不同的感覺'pay'!當你已經使用'Math.Round'時,也許使用字符串格式並不是必須的?如果你不想四捨五入實際的數字結構,但只想縮短產生的字符串,字符串格式化是一件好事。在這種情況下,請考慮使用格式化字符串「F」或「F2」(以及「N」,「N2」),例如'string.Format(「{0:N}支付)'或者等價地'pay.ToString(「N」)'。 –

+0

@JeppeStigNielsen你對第一行絕對正確!修訂。有趣的是,我以前從來沒有使用過'{0:N}',我認爲這是習慣的生物; o) –

+0

爲了進一步解釋,''F''四捨五入到當前文化的'NumberFormat'指定的小數位數的當前線程。這通常是兩位小數。 '「F2」總是四捨五入到兩位小數。 ''N「'和'」N2「'是相似的,但它們也根據文化插入組分隔符。例如'(11223344.5566m).ToString(「N」)'可能會在某種文化中產生格式化數字「11,223,344.56」。請參見[標準數字格式字符串](http://msdn.microsoft.com/zh-cn/library/dwhawy9k.aspx)。 –

2

確保您提供一個號碼,通常使用雙。 Math.Round可以帶1-3個參數,第一個參數是你想要的變量,第二個是小數位數,第三個是舍入類型。

double pay = 200 + bonus; 
double pay = Math.Round(pay); 
// Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even 
double pay = Math.Round(pay, 2, MidpointRounding.ToEven); 
// Rounds up to nearest number 
double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero); 
17

您應該使用一種形式Math.Round。請注意,除非您指定MidpointRounding值,否則Math.Round默認爲銀行家舍入(四捨五入爲最接近的偶數)。如果你不希望使用銀行家舍,你應該使用Math.Round(decimal d, int decimals, MidpointRounding mode),就像這樣:

Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01 
Math.Round(pay, 2, MidpointRounding.ToEven);  // .005 rounds to nearest even (0.00) 
Math.Round(pay, 2); // Defaults to MidpointRounding.ToEven 

Why does .NET use banker's rounding?

2

注重對事實Round

所以(我不知道,如果它在你的行業重要與否),而是:

float a = 12.345f; 
Math.Round(a,2); 

//result:12,35, and NOT 12.34 ! 

,使之成爲你的情況更精確,我們可以做這樣的事情:

int aInt = (int)(a*100); 
float aFloat= aInt /100.0f; 
//result:12,34 
+0

Math.Round不接受浮點數作爲參數。 –

相關問題