### 如何格式化十进制值而不进行舍入以在c＃中存储为可为空的十进制变量

``````31.818181818181818181818181818M  or 31.818181818181818181M or 31.81818M
``````

``````31.8181
``````

（不舍入至31.8182） 并将其存储到可以为空的十进制变量中。我试过关注decimal formatting without rounding .netStop Rounding In C# At A Certain Number 但是对于可以为空的小数字没有运气。

``````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;
}
``````

#### 2 个答案:

``````private decimal? ReturnNullableDecimal(decimal? initValue)
{
if (initValue.HasValue)
return Math.Truncate(10000 * initValue.Value) / 10000;
else
return null;
}
``````

``````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;
}
}
}
``````

e.g。

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