1

我有一个小数 = 123456 和一个整数 = 5 我想插入“。” 在我的小数点的第五位从右边得到 1.23456 我怎样才能使用标准格式化函数来做到这一点(即不除以 10 的幂,然后才格式化以添加缺失的零)?谢谢。

4

4 回答 4

1

这实际上很有趣,至少,我认为是。我希望我不会因为输入负数或考虑可能的十进制输入而愚蠢地过火......

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

            }
于 2013-03-01T21:23:05.200 回答
1

你想要这样的东西吗?

decimal d = 10000000;
int n=4;

string s = d.ToString();
var result = s.Substring(0, s.Length - n) + "." + s.Substring(s.Length - n);
于 2013-03-01T20:41:55.663 回答
0

您可以通过String.Insert做到这一点

decimal d = 100000000000;
string str = d.ToString();
int i = 5;
string str2 = str.Insert(str.Length - i, ".");
Console.WriteLine(str2);
Console.Read();
于 2013-03-01T21:14:40.900 回答
0

这很丑陋;真正的价值是什么?12345 还是 1.2345?为什么要存储 12345 然后尝试将其表示不同的数字?离开你试图传达你实际拥有的东西是一个定点(编码)值,你需要先解码它。IE

decimal fixedPoint = 12345
decimaldecoded = fixedPoint / (decimal)10000
decoded.ToString();

所以在你的代码中你应该定义你有一个

var fixedPoint = new FixedPointValue(12345, 5);
var realValue = fixedPoint.Decode();

如果任何其他程序员看到这个,很明显为什么你必须以这种方式格式化它。

于 2013-03-01T20:47:04.457 回答