2016-09-27 9 views
-2

ダブル変数の10進数2桁を文字列形式で表示したい。ゼロ以外の10進数を表示する関数を書くには?doubleはC#で2のゼロでない10進数を示しますか?

例:

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;'次に 'string s = string.Format( "{0:N2}%"、x); '。 3人全員。 –

+0

あなたのものを使用して@ KeyurPATEL、私は2.29を入力すると2.29を持っています....なぜですか? –

+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ラウンド)、小数点以下2桁の文字列に変換します。

それ以外の場合は、元の値を返し、文字列に変換します。

あなたのさらなるニーズに応じて、または出力文字列をもう少し微調整したい場合は、自由に機能を変更してください。

編集

個人的にテスト値:

1、1.1、1.11、1.111、1.138234732

結果:

1、1.1、1.11、1.11、1.13

関連する問題