问题
I am interested in how to round variables to two decimal places. In the example below, the bonus is usually a number with four decimal places. Is there any way to ensure the pay variable is always rounded to two decimal places?
pay = 200 + bonus;
Console.WriteLine(pay);
回答1:
Use Math.Round and specify the number of decimal places.
Math.Round(pay,2);
Math.Round Method (Double, Int32)
Rounds a double-precision floating-point value to a specified number of fractional digits.
Or Math.Round Method (Decimal, Int32)
Rounds a decimal value to a specified number of fractional digits.
回答2:
You should use a form of Math.Round. Be aware that Math.Round
defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode), like so:
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
(Why does .NET use banker's rounding?)
回答3:
decimal pay = 1.994444M;
Math.Round(pay , 2);
回答4:
You can round the result and use string.Format
to set the precision like this:
decimal pay = 200.5555m;
pay = Math.Round(pay + bonus, 2);
string payAsString = string.Format("{0:0.00}", pay);
回答5:
Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.
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);
回答6:
Pay attention on fact that Round
rounds.
So (I don't know if it matters in your industry or not), but:
float a = 12.345f;
Math.Round(a,2);
//result:12,35, and NOT 12.34 !
To make it more precise for your case we can do something like this:
int aInt = (int)(a*100);
float aFloat= aInt /100.0f;
//result:12,34
回答7:
Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.
var pay = 200 + bonus;
pay = System.Math.Round(pay, 2);
Console.WriteLine(pay);
MSDN References:
- http://msdn.microsoft.com/en-us/library/system.math.round.aspx
- http://msdn.microsoft.com/en-us/library/zy06z30k.aspx
回答8:
Console.WriteLine(decimal.Round(pay,2));
来源:https://stackoverflow.com/questions/12621640/rounding-a-variable-to-two-decimal-places-c-sharp