设置数据类型 decimal 的小数位数

Set the number of decimal places in data type decimal

我有一个模型,其中包含 属性 数据类型的小数。我想确保 getter 方法 returns 在每种情况下都是确定性的值。

数据类型模型存储了非有效小数位数,但似乎没有公开方法或属性来控制它。

以下程序说明了调查结果:

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

如何控制小数数据类型中使用的小数位数?

要更改十进制值的个数,我将小数转换为字符串,然后再转换回小数。您知道更清洁的方法吗?

0.00m加到一个十进制数上,虽然违反直觉,但会强制它至少有2个小数点。如果需要保证刚好是2,也可以申请decimal.Round()

    static decimal correctDecimalPlaces(decimal d)
    {
        return decimal.Round(d + 0.00m, 2);
    }

我是这样找到的(如果 return 字符串适合你):

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

或者我们这样使用:

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