取決於你想如何顯示百分比值,但我猜你會想顯示的百分比string
?怎麼樣:
string percentage = Math.Floor(NumA/NumB).ToString("0.00");
Console.WriteLine(Math.Floor(2.3).ToString("0.00")); //this will output 2.00
如果你想的位數後小數點配置,你可以事先創建掩蔽字符串,像這樣的東西:
private string CreateMaskingString(int numberOfDigits)
{
var sb = new StringBuilder("0.");
sb.Append(new string('0', numberOfDigits));
return sb.ToString();
}
和使用情況是這樣的:
Console.WriteLine(Math.Floor(2.3).ToString(CreateMaskingString(2))); //this will output 2.00
一個更加簡單和優雅的解決方案是這樣的,因爲已經指出的RomCoo:
string percentage = Math.Floor(NumA/NumB).ToString("F" + numberOfDigits);
這裏的「F」是什麼意思?您可以閱讀explanation here。但基本上:
定點(「F」)格式說明一個數字轉換爲的 形式的字符串「-ddd.ddd ...」,其中每個「d」表示一個數字(0-9) 。如果數字爲負,則 字符串以負號開頭。
相關:http://stackoverflow.com/questions/2375735/doing-a-math-roundx-2-on-a-decimal-value-but-need-to- sure-2-numbers-after-d – levelonehuman