10

Have decimal amount, want to trim to 2 decimal places if present

bdukes
  • 152,002
  • 23
  • 148
  • 175
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

5 Answers5

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
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
1

I use this: Math.Round(MyDecimalValue,2);

Sadjad Khazaie
  • 2,102
  • 22
  • 22
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
  • 2
    In 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
  • Right, sorry should be math.exp (). How is it off otherwise? – Chris Shain Jan 14 '11 at 19:40
  • `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