简体   繁体   中英

Rounding decimal number upto two decimal places

I am trying to round decimal number upto two decimal places which is working perfectly. I am doing as below :

Math.Round(Amount, 2)

So, if I have Amount as 40000.4567 , I am getting 40000.46 which is exactly what I want. Now problem is I have decimal number like 40000.0000 , when I round it, the result is 40000 , and what I really want is 40000.00 . So round will always neglect trailing zeros.

To solve this problem, I have the option of converting it to string and use format , but I don't want to do that as that will be inefficient and I believe there must be some way to do it better.

I also tried something like

Decimal.Round(Amount, 2)

Now one way can be to check whether number contains anything in fractional part and use round function accordingly , but that is really bad way to do it. I can't use truncate as well due to obvious reasons of this being related to amount.

What is the way around?

It is rounding correctly but you fail to understand that the value is not the format. There is no difference between the two values, 40000 and 40000.00 , and you'll have a similar issue with something like 3.1 .

Simply use formatting to output whatever number you have to two decimal places, such as with:

Console.WriteLine(String.Format("{0:0.00}", value));

or:

Console.WriteLine(value.ToString("0.00"));

You are mixing two things - rounding and output formatting. In order to output a number in a format you want you can use function string.Format with required format, for example:

decimal number = 1234.567m;
string.Format("{0:#.00}", number);

You can read more about custom numeric format strings in MSDN

I think what you're looking for is displaying two decimals, even if they are zero. You can use string.Format for this (I've also combined it with Round):

Console.WriteLine(string.Format("{0:0.00}", Math.Round(Amount, 2));

for rounding decimal number you can use

decimal number=200.5555m;
number= Math.Round(number, 2);
string numString= string.Format("{0:0.00}", number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM