2017-02-02 127 views
-6

我有一種方法,應該將十進制百分比轉換爲int 例如0,73應該返回73. 我做了下面的混亂,但想知道更好的解決方案。將十進制百分比轉換爲int

private static int ToPercentage(double d) 
     { 
      string temp = d.ToString("p"); 
      string temp2 = temp.Replace("%", ""); 
      double temp3 = Convert.ToDouble(temp2); 
      int result = (int) temp3; 
      return result; 
     } 
+8

return(int)(d * 100); –

+0

將數值轉換爲另一種數值時,*爲什麼*會將中間步驟格式化爲字符串並返回? – Amy

+0

這就像Code Golf的對面。 – Equalsk

回答

0

我感覺不好寫這個答案,但希望這會阻止所有其他答案,並關閉票。

private static int ToPercentage(double d) 
{ 
    return (int)(d*100); 
} 

編輯:謝謝Devid的建議:) TIL如何使一個社區維基發佈答案!

+1

如果你覺得這麼糟糕,那麼讓你的文章成爲一個社區wiki,這樣就沒有人能夠獲得積分。 – DavidG

+0

@DavidG,不知道你可以那樣做:)謝謝! – Roman

0

試試這段代碼。您不需要轉換爲字符串,然後執行替換。

private static int ToPercentage(double d) 
    { 
     int result = Convert.ToInt32(Math.Truncate(d * 100)); 
     return result; 
    } 
相關問題