2016-09-27 16 views
-2

我想顯示字符串格式的雙變量的最大2位小數。如何編寫一個函數來顯示非零小數?double在C#中顯示2個非零小數?

例子:

double intVar = 1; 
double oneDice = 1.1; 
double twoDice = 1.11; 
double threeDice = 1.111; 

Console.writeLine(yourFunction(intVar)); //output 1 
Console.writeLine(yourFunction(oneDice)); //output 1.1 
Console.writeLine(yourFunction(twoDice)); //output 1.11 
Console.writeLine(yourFunction(threeDice)); //output 1.11 
+2

從http://stackoverflow.com/a/2453982/6741868,你可以先'double x = Math.Truncate(threeDice * 100)/ 100;'then'string s = string.Format(「{0:N2}%」,x);'。他們全部3人。 –

+0

@KeyurPATEL通過使用你的,我得到2.29時輸入2.3 ....爲什麼? –

+0

我看到了問題。由於需要幾行代碼,我將把我的評論轉換爲答案。 –

回答

0

在我的評論鏈接,https://stackoverflow.com/a/2453982/6741868,和一點點其他代碼:

public string yourFunction(double val) 
{ 
    double x = val; 

    if (BitConverter.GetBytes(decimal.GetBits((decimal)val)[3])[2] > 2) //check if there are more than 2 decimal places 
    { 
     x = Math.Truncate(val * 100)/100;   
     string s = string.Format("{0:N2}", x); 
     return s; 
    } 
    return x.ToString(); 
} 

如果有超過2位小數,它會截斷其餘部分( NOT round)並轉換爲顯示2位小數的字符串。

否則它只是返回原始值,轉換爲字符串。

隨意根據您的進一步需要修改該功能,或者如果您想調整輸出字符串多一點。

編輯

親自測試值:

1,1.1,1.11,1.111,1.138234732

結果:

1,1.1,1.11,1.11,1.13