使用 std::fmt 格式化时,如何以可变数量填充数字? [英] How can I 0-pad a number by a variable amount when formatting with std::fmt?

查看:33
本文介绍了使用 std::fmt 格式化时,如何以可变数量填充数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在向用户显示字符串之前对其进行 0-pad 填充,例如

I'm looking to 0-pad a string before I display it to the user, e.g.

let x = 1234;
println!("{:06}", x); // "001234"

但是,我希望输出字符串的长度是可变的,例如它可以由用户的命令行参数设置:

However, I'd like the length of the output string to be variable, e.g. it could be set by a command line parameter from the user:

let x = 1234;
let width = 6;
println!("{:0*}", width, x); //fails to compile
// error: invalid format string: expected `'}'`, found `'*'`

与精度不同,0-padding 似乎不支持 * 来指定宽度.

Unlike precision, it doesn't seem that 0-padding supports the * for specifying a width.

我不是在寻找涉及手动填充的解决方案,因为重新实现 std::fmt 的一部分似乎很尴尬.

I'm not looking for solutions that involve manually padding, because it seems awkward to re-implement part of std::fmt.

推荐答案

您可以将 :0_ 格式说明符与变量一起使用:

You can use the :0_ format specifier with a variable:

println!("{:0width$}", x, width = width); // prints 001234

这里正在操场上运行

同样,如果width <= 4,它只会打印1234.如果 width = 60,则打印:

Likewise, if width <= 4, it just prints 1234. If width = 60, it prints:

000000000000000000000000000000000000000000000000000000001234

格式参数也支持序数,因此这也适用:

The format arguments also support ordinals, thus this also works:

println!("{:01$}", x, width);

std::fmt 的文档 有一个纲要print_! 宏支持的各种参数和修饰符.

The documentation for std::fmt has a rundown of the various parameters and modifiers the print_! macros support.

这篇关于使用 std::fmt 格式化时,如何以可变数量填充数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆