1

I have got a model which contains a property of data type decimal. I want to make sure the getter method returns a deterministic value in every case.

The data type model stores the number of non-significant decimal places, but does not seem to expose a method or property to control it.

The following program illustrates the findings:

class Program
{
    static void Main(string[] args)
    {
        decimal d1 = decimal.Parse("1200.00");
        Console.WriteLine(d1); // Prints 1200.00
        decimal d2 = decimal.Parse("1200");
        Console.WriteLine(d2); // Prints 1200
        decimal d3 = correctDecimalPlaces(d2);
        Console.WriteLine(d3); // Prints 1200.00
    }
    static decimal correctDecimalPlaces(decimal d)
    {
        return decimal.Parse(d.ToString("0.00"));
    }
}

How can I control the number of decimal places used in decimal data type?

To change the number of decimal values, I convert the decimal to a string and back to a decimal. Do you know a cleaner way to do it?

Adrian Dymorz
  • 875
  • 8
  • 25
  • Maybe this can answer you: https://stackoverflow.com/questions/48212254/set-the-precision-for-decimal-numbers-in-c-sharp – MyBug18 Mar 31 '20 at 08:29

2 Answers2

1

Adding 0.00m to a decimal number, although counterintuitive, will force it to have at least 2 decimal points. If you need to ensure it has exactly 2, you can apply decimal.Round() also.

    static decimal correctDecimalPlaces(decimal d)
    {
        return decimal.Round(d + 0.00m, 2);
    }
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
1

I found this way (if return string is good for you):

public static class Extensions
{
    public static string ToStringDecimal(this decimal d, byte decimals)
    {
        var fmt = (decimals>0) ? "0." + new string('0', decimals) : "0";
        return d.ToString(fmt);
    }

    public static string ToStringDecimal(this decimal? d, byte decimals)
    {
        if (!d.HasValue) return "";
        return ToStringDecimal(d.Value, decimals);
    }
}

Or we use like this:

 public static decimal? RoundTo2Decimal(decimal? pValue)   
        if (pValue.HasValue)
        {
            if (pValue.Value >= 0)
            {
                decimal vAluePos = pValue.Value * 100 + 0.5m;
                return Math.Floor(vAluePos) / 100;
            }

            decimal vAlueNeg = Math.Abs(pValue.Value) * 100 + 0.5m;
            return -(Math.Floor(vAlueNeg) / 100);
        }
        return null;
    }
Bence Végert
  • 728
  • 10
  • 12