2016-03-08 86 views
-1

我需要在小數點後顯示兩位數,並以百分比四捨五入至floor。我寫出了這樣的代碼,但這看起來太複雜了,是否有另一種更有效的方法呢?Math.Floor小數點後面的x位數

double decimalPlacesFactor =Math.Pow(10, numberOfDigits+2); 
percentage = Math.Floor((NumA/NumB)*decimalPlacesFactor)/decimalPlacesFactor *100; 

輸出應該看起來像

99.78 % 
+0

相關:http://stackoverflow.com/questions/2375735/doing-a-math-roundx-2-on-a-decimal-value-but-need-to- sure-2-numbers-after-d – levelonehuman

回答

0

使用ToString()方法將您的號碼轉換爲字符串。通過使用參數「FX」將其顯示爲具有X位數的浮點。例如「F2」 的兩個數字

string percentage = Math.Floor(NumA/NumB).ToString("F"+numberOfDigits); 
+0

你能解釋你的解決方案的工作原理嗎?這對其他訪問者來說會很好。順便說一句,內部的'ToString'是不必要的。 – Koopakiller

0

取決於你想如何顯示百分比值,但我猜你會想顯示的百分比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) 。如果數字爲負,則 字符串以負號開頭。

+0

這是一個很好的解決方案,但我想通過指定「numberOfDigits」中的位數來保持此配置。 –

+0

已更新我的答案。 – Peroxy

+0

@Peroxy你可以使用'新字符串'('0',numberOfDigits)'而不是'for'循環。我認爲這更具可讀性。 – Koopakiller

相關問題