0

I have tried to format(Truncate) a decimal value to 4 decimal places. For example, I want to convert decimal numbers like

31.818181818181818181818181818M  or 31.818181818181818181M or 31.81818M 

to

31.8181 

(NOT rounding to 31.8182) And store it in to a nullable decimal variable. I have tried following decimal formatting without rounding .net and Stop Rounding In C# At A Certain Number but no luck for nullable decimals.

Here is the code

private decimal? ReturnNullableDecimal(decimal? initValue)
{
        //e.g. initValue = 35M;
        initValue = 35M; //just to debug;

        decimal? outputValue = null;


        if (initValue != null)
            outputValue = initValue / (decimal)1.10;
        //now outputValue is 31.818181818181818181818181818M
        outputValue = Convert.ToDecimal(string.Format("{0:0.0000}", outputValue)); // <- this should be 31.8181 but gives 31.8182

        return outputValue;
    }

Can someone please help?

Community
  • 1
  • 1
Dush
  • 1,185
  • 26
  • 29

2 Answers2

2

Any decimal can be implicitly converted to a decimal?, so the same code works as in any other example of truncating. If your input is also a decimal?, you'll have to check for null there.

private decimal? ReturnNullableDecimal(decimal? initValue)
{
    if (initValue.HasValue)
        return Math.Truncate(10000 * initValue.Value) / 10000;
    else
        return null;
}
user12864
  • 581
  • 4
  • 7
0

Based on accepted answer I created an Extension

namespace your.namespace.Extensions
{
    public static class NullableDecimalExtension
    {
        public static decimal? FormatWithNoRoundingDecimalPlaces(this decimal? initValue, int decimalPlaces)
        {
            if (decimalPlaces < 0)
            {
                throw new ArgumentException("Invalid number. DecimalPlaces must be greater than Zero");
            }

            if (initValue.HasValue)
                return (decimal?)(Math.Truncate(Math.Pow(10, decimalPlaces) * (double)initValue.Value) / Math.Pow(10, decimalPlaces));
            else
               return null;
        }
    }
}

Usage: Add using your.namespace.Extensions; to the class

Then in the calling method it can directly call

e.g.

initValue = 35M;
decimal? outputValue = (initValue / (decimal)1.10).FormatWithNoRoundingDecimalPlaces(4);
//now the outputValue = 31.8181

If we need to get 2 decimal places just use .FormatWithNoRoundingDecimalPlaces(2);

Dush
  • 1,185
  • 26
  • 29