Have decimal amount, want to trim to 2 decimal places if present
Asked
Active
Viewed 3.2k times
10
-
Do you want to just "lop off the excess decimals" or do you want to round like Jon says? – Steve Danner Jan 14 '11 at 19:29
-
1Truncate or Round? To Truncate see: http://stackoverflow.com/questions/329957/truncate-decimal-number-not-round-off – SwDevMan81 Jan 14 '11 at 19:31
5 Answers
23
Have you tried using value = Decimal.Round(value, 2)
?
For example:
using System;
class Test
{
static void Main()
{
decimal d = 1234.5678m;
Console.WriteLine("Before: {0}", d); // Prints 1234.5678
d = decimal.Round(d, 2);
Console.WriteLine("After: {0}", d); // Prints 1234.57
}
}
Note that this is rounding rather than just trimming (so here it's rounded up)... what exactly do you need? Chances that the Decimal
struct supports whatever you need to do. Consult MSDN for more options.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
Math.Round can do banker's rounding. http://msdn.microsoft.com/en-us/library/ms131275.aspx – Hamish Grubijan Jan 15 '11 at 19:18
12
decimal.Truncate(myDecimal * 100) / 100
This would cut away everything following the first two decimal places. For rounding see Jon's answer.

Joey
- 344,408
- 85
- 689
- 683
1
If its just for display purposes, you can use:
Console.Out.WriteLine("Number is: {0:F2}", myDecimalNumber);

gap
- 2,766
- 2
- 28
- 37
0
This should work (EDIT: Fixed to remove rounding):
((Int32)(value * Math.Pow(10, decimalPlaces))) / (Math.Pow(10D, decimalPlaces));

Chris Shain
- 50,833
- 6
- 93
- 125
-
2In C# `^` is `xor`. Also, if someone uses `decimal` chances are it's a deliberate choice and they probably don't want another type (apart from that your example is way off in any case). – Joey Jan 14 '11 at 19:34
-
-
`Int` is not a type in C# and you're doing integer division afterwards, leaving no decimal places anyway. – Joey Jan 14 '11 at 19:46