Best way to achieve complicated numeric formatting in C#

浪子不回头ぞ 提交于 2019-12-05 20:12:42

You could write it like this, generating a standard format string and then using it:

public static string Format(decimal input, int width, int precision)
{
    var format = string.Format("{{0,{0}:F{1}}}", width, precision);
    // generates (e.g. width=15, precision=5)  "{0,15:F5}"
    // then format using this and replace padding with zeroes
    return string.Format(format, input).Replace(" ", "0");
}

Or instead of calling format twice just concat the format string, depending on your preference:

string.Format("{0," + width + ":F" + precision + "}", input).Replace(" ","0")

You have to replace the spaces afterwards since there's no way to specify the padding character. Alternately you could write your own formatter to pad with a specific character. This works though :)

Edit: This matches the original for all inputs except when precision = 0. In that case, the original is incorrect, since it counts the decimal point as part of the width even when it isn't present.

Oops: Forgot to check negative numbers.

Here is a simpler version, but have to check if the number is negative to get the padding correct:

public override string Format(decimal input, int width, int precision)
{
    var output = input.ToString("F" + precision);
    return input < 0
        ? "-" + output.Substring(1).PadLeft(width, '0')
        :       output             .PadLeft(width, '0');
}

Something like this:

return input.ToString(new string('0', width) + '.' + new string('0', precision));

?

Edit: acutally, here's a better one:

return input.ToString(new string('0', width - 1).insert(width - precision, '.'));

Well, one way to get rid of the ZERO would be

public override string Format(decimal input, int width, int precision)
{
    String formatString = new string('0', width - precision - 1) 
                      + "." + new string('0', precision);
    return ToDecimal(input).ToString(formatString);
}

Not sure if you can do much else.

This is about as good as it gets:

public static string double2string( double value , int integerDigits , int fractionalDigits )
{
  string        decimalPoint = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator ;
  StringBuilder sb           = new StringBuilder() ;

  sb.Append('0',integerDigits)
    .Append(decimalPoint)
    .Append('0',fractionalDigits)
    ;
  return value.ToString( sb.ToString() ) ;
}

I beleive you could just call Decimal.ToString and pass it a Custom Numeric Format String that you can generate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!