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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:22:48  来源:igfitidea点击:

padding zero on floating point bash printf

bashprintfprecision

提问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.