Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

math

decimal

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

like image 701
Blankman Avatar asked Jan 14 '11 19:01

Blankman


4 Answers

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

like image 32
Sadjad Khazaie Avatar answered Nov 20 '22 15:11

Sadjad Khazaie


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.

like image 184
Jon Skeet Avatar answered Nov 20 '22 17:11

Jon Skeet


decimal.Truncate(myDecimal * 100) / 100

This would cut away everything following the first two decimal places. For rounding see Jon's answer.

like image 12
Joey Avatar answered Nov 20 '22 16:11

Joey


If its just for display purposes, you can use:

Console.Out.WriteLine("Number is: {0:F2}", myDecimalNumber);
like image 1
gap Avatar answered Nov 20 '22 17:11

gap