十进制格式
本文关键字:格式 十进制 | 更新日期: 2023-09-27 18:01:42
我有一个小数= 123456和一个整数= 5我想在小数点右边的第五位插入"。",得到1.23456我怎么能做到这一点与标准格式化功能(即不除以10的幂,然后格式化添加缺失的零)?谢谢。
你想要这样的东西吗?
decimal d = 10000000;
int n=4;
string s = d.ToString();
var result = s.Substring(0, s.Length - n) + "." + s.Substring(s.Length - n);
这实际上很有趣,至少我认为是这样。我希望我没有愚蠢地抛出负数,或者考虑可能的十进制输入…
decimal input;
int offset;
string working = input.ToString();
int decIndex = working.IndexOf('.');
if (offset > 0)
{
if (decIndex == -1)
{
working.PadLeft(offset, '0');
working.Insert(working.Length - offset, ".");
}
else
{
working.Remove(decIndex, 1);
decIndex -= offset;
while (decIndex < 0)
{
working.Insert(0, "0");
decIndex++;
}
working.Insert(decIndex, ".");
}
}
else if (offset < 0)
{
if (decIndex == -1)
{
decIndex = working.Length();
}
if (decIndex + offset > working.Length)
{
working.PadRight(working.Length - offset, '0');
}
else
{
working.Remove(decIndex, 0);
working.Insert(decIndex + offset, ".");
}
}
这很难看;真正的价值是什么?12345还是1.2345?为什么要存储12345,然后尝试将其表示为不同的数字?你想要传达的实际上是一个定点(编码)值,你需要先解码它。例如
decimal fixedPoint = 12345
decimaldecoded = fixedPoint / (decimal)10000
decoded.ToString();
所以在你的代码中你应该定义一个
var fixedPoint = new FixedPointValue(12345, 5);
var realValue = fixedPoint.Decode();
如果其他程序员看到这一点,就会明白为什么必须以这种方式格式化它。
您可以通过String来实现。插入
decimal d = 100000000000;
string str = d.ToString();
int i = 5;
string str2 = str.Insert(str.Length - i, ".");
Console.WriteLine(str2);
Console.Read();