Rounding a variable to two decimal places C# [dupl

2020-06-07 06:27发布

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);

8条回答
该账号已被封号
2楼-- · 2020-06-07 06:35

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);
查看更多
老娘就宠你
3楼-- · 2020-06-07 06:36
Console.WriteLine(decimal.Round(pay,2));
查看更多
一夜七次
4楼-- · 2020-06-07 06:40

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楼-- · 2020-06-07 06:42

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?)

查看更多
【Aperson】
6楼-- · 2020-06-07 06:50

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:

查看更多
Animai°情兽
7楼-- · 2020-06-07 06:53
decimal pay  = 1.994444M;

Math.Round(pay , 2); 
查看更多
登录 后发表回答