【发布时间】:2010-01-26 08:05:02
【问题描述】:
我有以下方法:
public static string ReturnFormat(string input, int maxLength, int decimalPrecision, char formatChar)
{
string[] format = new string[2];
string[] inputs = new string[2];
inputs = input.Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (input.Length > maxLength)
{
int offset = 0;
int counter = 0;
if (inputs[0].Length > maxLength - (1 + decimalPrecision))
{
offset = maxLength - (1 + decimalPrecision);
}
else
offset = inputs[0].Length;
for (int i = 0; i < offset; i++)
{
format[0] += formatChar;
if (counter < decimalPrecision)
{
format[1] += '0';
counter++;
}
}
System.Windows.Forms.MessageBox.Show("{0:" + format[0] + "." + format[1] + "}");
return String.Format(CultureInfo.CurrentCulture, "{0:" + format[0] + "." + format[1] + "}", input);
}
else
return input;
}
说我使用的是:
ReturnFormat("12.3456789011243", 10, 2, '#') // format is {0:##.00} // output 12.3456789011243
ReturnFormat("12345678901.1243", 10, 2, '#') // format is {0:#######.00} // output 12345678901.1243
现在我的问题是输入字符串的格式不正确,但格式字符串似乎还可以。 关于我做错了什么的任何想法?
【问题讨论】:
-
我想要的输出是 1234568.12
-
另外,这是一个非常奇怪的格式函数,我很难弄清楚什么时候需要它。
-
这将用于在 TextBox 中显示结果,并且 TextBox 它相当小,结果不适合用户的视觉范围。我的意思是 TextBox 可以存储大量值,但用户将无法看到正确的结果,而且文本框也是只读的。
-
那么我建议您在开始缩短整数部分之前删除小数。我认为这种缩短方式会让用户非常困惑,而且实际上是完全错误的。
-
好的,所以基本上我正在研究转换器,并且我有一个关于数字精度的选项。当我从单位 A 转换为单位 B 时,结果类似于 12345678901.1243 现在如果精度设置为 2,则转换后的值最多应包含 2 位数字。在我的情况下,数字是 12345678901.1243,这意味着 1234567890 并且 NumberDecimalSeparator 之后没有值。那将是正确的,因此只有像 12.3456789011243 这样的值将被处理为 12.35)对不起我的英语。我不确定我的解释是否正确。