我该怎么强迫' +'使用格式时正面浮动前的标志!宏?

时间:2018-05-24 21:57:17

标签: rust string-formatting

我想要使用format!宏格式化的右对齐浮点数,并且该符号始终可见。使用syntax specification我设计了以下格式:

format!("{:>10+.1}", 23.3434);

但是我遇到了编译错误:

error: invalid format string: expected `'}'`, found `'+'`
 --> src/main.rs:2:21
  |
2 |     let x = format!("{:>10+.1}", 23.3434);
  |                     ^^^^^^^^^^^

我正在使用Rust 1.25.0。

1 个答案:

答案 0 :(得分:6)

规范清楚地给出了[[fill]align][sign]['#']['0'][width]的顺序:

align := '<' | '^' | '>'
sign := '+' | '-'

因此,您不能在>+之间加上一个数字,宽度会在符号后面显示:

format!("{:>10+.1}", 23.3434);

这呈现为" +23.3"。鉴于:

format!("{:>+010.1}", 23.3434);

呈现为+0000023.3

虽然为了可维护性,我建议使用

format!("{:>+0width$.prec$}", 23.3434, width=10, prec=1);
相关问题