変数を小数点以下2桁に丸める方法に興味があります。以下の例では、ボーナスは通常、小数点以下4桁の数字です。支払い変数が常に小数点以下第2位に四捨五入されるようにする方法はありますか?
pay = 200 + bonus;
Console.WriteLine(pay);
Math.Roundを使用して、小数点以下の桁数を指定します。
Math.Round(pay,2);
倍精度浮動小数点値を指定された小数桁数に丸めます。
またはMath.Roundメソッド(Decimal、Int32)
10進値を指定された小数桁数に丸めます。
の形式を使用する必要がありMath.Round
ます。Math.Round
値を指定しない限り、デフォルトはバンカー四捨五入 (最も近い偶数への四捨五入) になることに注意してくださいMidpointRounding
。バンカーの丸めを使用したくない場合は、次のMath.Round(decimal d, int decimals, MidpointRounding mode)
ようにを使用する必要があります。
Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven); // .005 rounds to nearest even (0.00)
Math.Round(pay, 2); // Defaults to MidpointRounding.ToEven
decimal pay = 1.994444M;
Math.Round(pay , 2);
結果を丸めて、次のstring.Format
ように精度を設定するために使用できます。
decimal pay = 200.5555m;
pay = Math.Round(pay + bonus, 2);
string payAsString = string.Format("{0:0.00}", pay);
System.Math.Roundを使用して、小数値を指定された小数桁数に丸めます。
var pay = 200 + bonus;
pay = System.Math.Round(pay, 2);
Console.WriteLine(pay);
MSDNリファレンス:
必ず数値を指定してください。通常は double が使用されます。Math.Round は 1 ~ 3 個の引数を取ることができます。最初の引数は丸めたい変数、2 番目は小数点以下の桁数、3 番目は丸めのタイプです。
double pay = 200 + bonus;
double pay = Math.Round(pay);
// Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even
double pay = Math.Round(pay, 2, MidpointRounding.ToEven);
// Rounds up to nearest number
double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero);
という事実に注意してRound
ください。
だから(それがあなたの業界で重要かどうかはわかりません)、しかし:
float a = 12.345f;
Math.Round(a,2);
//result:12,35, and NOT 12.34 !
あなたのケースをより正確にするために、次のようなことができます:
int aInt = (int)(a*100);
float aFloat= aInt /100.0f;
//result:12,34
Console.WriteLine(decimal.Round(pay,2));