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:55

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 
查看更多
劳资没心,怎么记你
3楼-- · 2020-06-07 06:57

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.

查看更多
登录 后发表回答