2012-08-13 43 views
3

我有一個價格的文本框,我想得到一個小數點後兩位小數,不管原始字符串是一個十進制還是整數。例如:如何將C#中的文本框中的數字舍入爲2位小數?

input = 12 --> output = 12.00 
input = 12.1 --> output = 12.10 
input = 12.123 --> output = 12.12 
+1

要知道,公認的答案給你一個字符串,它可能並不總是你想要的。例如,'(12.125m).ToString(「N」)''是12.13「',並且'(12.135m).ToString(」N「)''是12.14」'('AwayFromZero'四捨五入)。但是'Math.Round(12.125m,2);'是'12.12',而'Math.Round(12.135m,2);'是'12.14'。小心! – hmqcnoesy 2012-08-13 12:45:10

回答

3

使用這種方法decimal.ToString("N");

5

可以使用.ToString()重載接受一個字符串格式:

var roundedInput = input.ToString("0.00"); 

。當然,這會導致一個字符串類型。

要簡單的圓形,可以使用Math.Round

var roundedInput = Math.Round(input, 2); 

你應該知道,在默認情況下,Math.Round使用「銀行家舍入」的方法,你可能不希望。在這種情況下,您可能需要使用採用四捨五入類型枚舉超載:

var roundedInput = Math.Round(input, 2, MidpointRounding.AwayFromZero); 

看到,這裏使用MidpointRounding的方法重載文檔:http://msdn.microsoft.com/en-us/library/ms131275.aspx

另外要注意的是,默認四捨五入方法Math.Rounddecimal.ToString()中使用的默認舍入方法不同。例如:

(12.125m).ToString("N"); // "12.13" 
(12.135m).ToString("N"); // "12.14" 
Math.Round(12.125m, 2); // 12.12 
Math.Round(12.135m, 2); // 12.14 

根據您的情況,使用錯誤的技術可能會非常糟糕!

3
// just two decimal places 
String.Format("{0:0.00}", 123.4567);  // "123.46" 
String.Format("{0:0.00}", 123.4);   // "123.40" 
String.Format("{0:0.00}", 123.0);   // "123.00" 
0

嘗試

Input.Text = Math.Round(z, # Places).ToString(); 
+0

這將返回四捨五入的答案,但未按要求完成格式設置 – SeanC 2012-08-13 14:03:38