仅打印小数值

  • 本文关键字:小数 打印 c# .net
  • 更新时间 :
  • 英文 :


例如:

decimal test = 5.021m;

我想在小数点后打印 4 位小数(所以在这种情况下,0210)。我能想到的唯一解决方案是

decimal test = 50.021m;
test.ToString("0.0000").Split('.')[1].Dump();

它确实打印了0210...,但对我来说似乎非常愚蠢。有没有更好的格式可以用来做到这一点?

我建议对分数使用扩展方法(或静态方法,如果您愿意的话)。不幸的是,通用版本很棘手,尽管可以改为:

public static decimal Fraction(this decimal d) => d - Math.Truncate(d);
public static TNum Fraction<TNum>(this TNum d) => d - Math.Truncate((dynamic)d);

然后你可以格式化分数:

decimal test = 50.021m;
test.Fraction().ToString(".0000").Substring(1).Dump();

另一种选择是使用模运算符:

(test % 1).ToString(".0000").Substring(1).Dump();

更新:我添加了一个Substring来跳过小数分隔符,假设它是一个字符。

代替数学,你可以做字符串处理,但不是Split的开销,只需使用SubstringIndexOf

((Func<string, string>)((s) => s.Substring(s.IndexOf('.')+1)))(test.ToString(".0000",CultureInfo.InvariantCulture)).Dump();

作为扩展方法:

public static string Fractional4<TNum>(this TNum num) {
    var strNum = ((IFormattable)num).ToString(".0000", CultureInfo.InvariantCulture);
    return strNum.Substring(strNum.IndexOf('.')+1);
}

你可以打电话给哪个

test.Fractional4().Dump();

您可以使用 Math:

decimal test = 50.021m;
decimal absTest = Math.Abs(test);
decimal floor = Math.Floor(absTest);                       // 50
decimal digits = Math.Floor((absTest - floor) * 10000);    // 210
string output = digits.ToString("0000")                    // if you need the leeding 0

解释:

首先,您需要取test值的绝对值,因为Math.Floor()

返回小于或等于指定的双精度浮点数的最大整数。

取您的值的底价并从绝对test值中减去它后,您将获得一个增量。现在,您必须将增量乘以Math.Pow(10, NumberOfDigits]),然后用另一个Math.Floor剪切小数位。


作为扩展方法:

public static decimal GetDecimalPlaces(this decimal value, int numberOfPlaces)
{
    decimal absoluteValue = Math.Abs(value);
    decimal floor = Math.Floor(absoluteValue);
    decimal delta = absoluteValue - floor;
    decimal decimalPlaces = Math.Floor(delta * (decimal)Math.Pow(10, numberOfPlaces));
    return decimalPlaces;
}

用法:

decimal posTest = 50.0210m;
decimal negTest = -50.0210m;
// Output: 0210
Console.WriteLine( posTest.GetDecimalPlaces(4).ToString("0000") );
// Output 021
Console.WriteLine( negTest.GetDecimalPlaces(3).ToString("000") );

还可以在 1.0 除以显示数字后编辑剩余部分。

        decimal test = 5.021m;
        Debug.Print(string.Format("{0:0000}", test % 1.0m * 10000));

最新更新