bash 在浮点bash printf上填充零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14565863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
padding zero on floating point bash printf
提问by lev.tuby
I would like to have a floating point number printed in bash with padded zeroes to fill a range %5.3f. I know of printf function.
我想在 bash 中打印一个带有填充零的浮点数来填充范围 %5.3f。我知道 printf 函数。
My problem is the following:
我的问题如下:
printf "0%5.3f\n" 3.00
returns, as expected,
正如预期的那样返回,
03.000
but the line
但这条线
printf "0%5.3f\n" 23.00
gives instead
给
023.000
which is not what I want of course.
这当然不是我想要的。
Any suggestion?
有什么建议吗?
回答by Michael Wild
You have to put the 0afterthe %:
你必须把0之后的%:
printf "%06.3f\n" 23.00
Notice that I also increased the minimum field width to 6, otherwise no padding will occur (3 decimal places, one dot, leaves just a single digit in front of the decimal point).
请注意,我还将最小字段宽度增加到 6,否则不会出现填充(3 个小数位,一个点,在小数点前只留下一个数字)。
回答by Axel
If anything at all, the 0 would have to be on the right side of the percent sign. I don't have a linux system at work, but try printf "%05.3f\n" 23.00.
如果有的话,0 必须在百分号的右侧。我没有在工作的 linux 系统,但试试printf "%05.3f\n" 23.00.

