例如:
decimal test = 5.021m;
我想在小数点后打印4位小数(所以在这种情况下,0210)。我能想到的唯一解决方案是
decimal test = 50.021m;
test.ToString("0.0000").Split('.')[1].Dump();
打印0210 ...但对我来说似乎非常愚蠢。我可以使用更好的格式来做到这一点吗?
答案 0 :(得分:3)
我会为分数建议一个扩展方法(或静态方法,如果你愿意)。不幸的是,通用版本很棘手,但可以改为:
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
的开销,只需使用Substring
和IndexOf
:
((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();
答案 1 :(得分:2)
您可以使用数学:
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
值中减去它之后,您将得到一个delta。现在,您必须将delta与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") );
答案 2 :(得分:1)
也可以在用显示位数除以1.0后编辑剩余部分。
decimal test = 5.021m;
Debug.Print(string.Format("{0:0000}", test % 1.0m * 10000));