如何在不舍入的情况下格式化十进制值以存储到c#中可为null的十进制变量中

本文关键字:十进制 变量 null 存储 不舍 舍入 情况下 格式化 | 更新日期: 2023-09-27 18:29:54

我尝试将一个十进制值格式化(截断)为小数点后4位。例如,我想转换像这样的十进制数字

31.818181818181818181818181818M  or 31.818181818181818181M or 31.81818M 

31.8181 

(未四舍五入到31.8182)并将其存储到一个可为null的十进制变量中。我尝试过在不舍入.net的情况下使用十进制格式,并在C#中的某个数字处停止舍入但可为零的小数没有运气。

这是代码

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

有人能帮忙吗?

如何在不舍入的情况下格式化十进制值以存储到c#中可为null的十进制变量中

任何decimal都可以隐式转换为decimal?,因此与任何其他截断示例中的代码相同。如果您的输入也是decimal?,则必须在那里检查null。

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

用法:添加使用您的.namespace.Extensions;至类

然后在调用方法中可以直接调用

例如

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

如果我们需要得到2个小数位,只需使用.FormatWithNoRoundingDecimalPlaces(2);