尾随和前导零字符串格式

时间:2012-04-05 10:48:54

标签: c# .net string-formatting tostring

生成此

所需的ToString格式是什么
>     5  to 00000500
>     10 to 00001000
>     15 to 00001500
>     20 to 00002000

感谢。

4 个答案:

答案 0 :(得分:4)

如果你想纯粹使用ToString格式字符串,而不是涉及乘法,那么你可以使用这样的东西:

string yourString = yourNumber.ToString("000000'00'");

答案 1 :(得分:3)

尝试

(yourNum * 100).ToString("0000000");

答案 2 :(得分:2)

(number * 100).ToString("D8");

答案 3 :(得分:1)

您可以使用自定义格式提供程序执行此操作。提供,输入是一个字符串。它很容易更改为任何数据类型。只需将if (arg.GetType() == typeof(String))更改为您要格式化的任何内容。

用法:

            var five = "5";
            var ten = "10";
            var fiveteen = "15";
            var twenty = "20";

        var formatprovider = new CustomStringFormatProvider();
        var res1 = string.Format(formatprovider, "{0}", five);
        res1 = string.Format(formatprovider, "{0}", ten);
        res1 = string.Format(formatprovider, "{0}", fiveteen);
        res1 = string.Format(formatprovider, "{0}", twenty);

这是格式提供者

public sealed class CustomStringFormatProvider : IFormatProvider, ICustomFormatter
{
    public Object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter)) return this;
        return Thread.CurrentThread.CurrentCulture.GetFormat(formatType);
    }
    public String Format(String format, Object arg, IFormatProvider formatProvider)
    {
        String s;

        IFormattable formattable = arg as IFormattable;

        if (formattable == null) s = arg.ToString();
        else s = formattable.ToString(format, formatProvider);

        if (arg.GetType() == typeof(String))
            return String.Join("",Enumerable.Repeat("0", 4).ToArray()) + s + String.Join("",Enumerable.Repeat("0", 4 - s.Length).ToArray());
        return s;
    }
}