.NET中的动态数字格式?

时间:2010-09-15 12:26:13

标签: c# number-formatting

我遇到了问题,无法找到解决方案。我有数字(十进制),如85.12343或100或1.123324。我想格式化这个结果总是13个字符长,包括分隔符。

100 - > 100.000000000
1.123324 - > 1.12332400000

我尝试使用toString,但失败了。我怎么能这样做?

谢谢:)

7 个答案:

答案 0 :(得分:8)

int digits = 13;
decimal d = 100433.2414242241214M;
int positive = Decimal.Truncate(d).ToString().Length;
int decimals = digits - positive - 1; //-1 for the dot
if (decimals < 0)
    decimals = 0;
string dec = d.ToString("f" + decimals);

在需要时,它不会从整个部分删除数字,只删除分数。

答案 1 :(得分:4)

我会选择Kobi's answer,除非你可以开始使用更多而不是13位,在这种情况下你可能需要做这样的事情(警告:我甚至没有尝试来提高效率;当然,如果有必要,还有一些方法可以优化:

public static string ToTrimmedString(this decimal value, int numDigits)
{
    // First figure out how many decimal places are to the left
    // of the decimal point.
    int digitsToLeft = 0;

    // This should be safe since you said all inputs will be <= 100M anyway.
    int temp = decimal.ToInt32(Math.Truncate(value));
    while (temp > 0)
    {
        ++digitsToLeft;
        temp /= 10;
    }

    // Then simply display however many decimal places remain "available,"
    // taking the value to the left of the decimal point and the decimal point
    // itself into account. (If negative numbers are a possibility, you'd want
    // to subtract another digit for negative values to allow for the '-' sign.)
    return value.ToString("#." + new string('0', numDigits - digitsToLeft - 1));
}

示例输入/输出:

Input                     Output
---------------------------------------
100                       100.000000000
1.232487                  1.23248700000
1.3290435309439872321     1.32904353094
100.320148109932888473    100.320148110
0.000383849080819849081   .000383849081
0.0                       .000000000000

答案 2 :(得分:1)

除了简单填充字符串之外,你还可以做一些更精细的数学来确定数字位数:

String FormatField(Int32 fieldWidth, Decimal value) {
  var integerPartDigits =
    value != Decimal.Zero ? (int) Math.Log10((Double) value) + 1 : 1;
  var fractionalPartDigits = Math.Max(0, fieldWidth - integerPartDigits - 1);
  return value.ToString("F" + fractionalPartDigits);
}

请注意,如果值为负数或具有比字段宽度少一位的整数部分,则无法获得所需的结果。但是,您可以根据您希望格式化和对齐这些数字的方式修改代码以适应这些情况。

答案 3 :(得分:1)

快'n'脏:

return (value.ToString("0.#") + "0000000000000").Substring(0, 13);

答案 4 :(得分:1)

string formatted = original.ToString("0.000000000000").Remove(13);

答案 5 :(得分:0)

怎么样?
string newString;
if (original.ToString().Length >= 13)
{
    newString = original.ToString().Substring(13);
}
else
{
    newString = original.ToString().PadRight(13, '0');
}

答案 6 :(得分:0)

int noofdecimal=3;
double value=1567.9800
value.ToString("#." + new string('0', noofdecimal));

//Result=1567.980