-2

I have a value 100.0000. I need truncate it to only two decimal places like 100.00 I need to do it when it have 00's in 3rd and 4 places. How to do it??

  • 1
    We need more info. What do you mean when you say you have a value that is `100.0000`, is that a `string`? Because, if it's a `double` then they automatically truncate the ending zeroes. – Sach Oct 23 '19 at 20:52

3 Answers3

1

If you want to handle financial values, you must use decimal. To another type of properties, you can use double

Based on my experience, you don't want to truncate because if you truncate, you'll lose part of the value. I think you want to round. In c#, you can round using Math.Ceiling()

double result = Math.Ceiling(value);

But, if you still want to truncate the value to two decimal places, you can do it two ways, using, for example, string interpolation:

if you want formated string:

Console.WriteLine($"{value:N2}");

if you don't need formated string:

Console.WriteLine($"{value:F2}");
pncsoares
  • 63
  • 10
0

Easy: all you have to do is use the format specifier as an argument to the ToString() method. In this case it would be "F2":

double value = 100.0000;
Console.WriteLine(value.ToString("F2"));
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
  • Please describe in your answer, what was the problem, and how will this snippet solve it, to help others understand this answer – FZs Oct 24 '19 at 04:41
0

decimal dec = 100.000;

dec .ToString ("#.##"); // returns "" when decimalVar == 0

and if you want to keep it as decimal not string use

dec = Math.Round( dec ,  2 , MidpointRounding.ToEven);

for more details follow this link

https://learn.microsoft.com/en-us/dotnet/api/system.decimal.round?redirectedfrom=MSDN&view=netframework-4.8#System_Decimal_Round_System_Decimal_System_Int32_System_MidpointRounding_

Islam Assem
  • 1,376
  • 13
  • 21