Linux 如何在bash函数中将数字显示为两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13632001/
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
How to display number to two decimal places in bash function
提问by Neilos
How should I take a number that is in hundreths of seconds and display it in seconds to two decimal places? Psuedo code to follow the dTime function I am not sure about but you'll get what I'm aiming for I think.
我应该如何取一个以百分之一秒为单位的数字并以秒为单位显示两位小数?遵循 dTime 函数的伪代码我不确定,但您会得到我认为的目标。
function time {
echo "$(date +%N)/10000000"
}
function dTime {
echo "(/100).(${:${#1}-3:${#1}-1})"
}
T=$time
sleep 2
T=$dTime T
采纳答案by Alex Howansky
Bash has a printf function built in:
Bash 有一个内置的 printf 函数:
printf "%0.2f\n" $T
回答by gniourf_gniourf
The following divides the output of date +%N
by 1000000000
, rounds the result to two decimal places and assigns the result to the variable T
.
下面对date +%N
by的输出进行1000000000
除法,将结果四舍五入到两位小数并将结果分配给变量T
。
printf -v T "%.2f" $(bc -l <<< "$(date +%N)/1000000000")
If you just want to print the stuff,
如果你只是想打印这些东西,
bc <<< "scale=2; $(date +%N)/1000000000"
If you don't like bc
and want to use dc
(which is a bit lighter and much funnier to use as it's reverse polish),
如果你不喜欢bc
并想使用dc
(因为它是反向抛光,使用起来更轻巧,更有趣),
dc <<< "2 k $(date +%N) 1000000000 / p"
Notice the difference, with printf
you'll have the leading 0
, not with bc
and dc
. There's another difference between printf
and bc
(or dc
): printf
rounds to the nearest number to two decimal places, whereas bc
(or dc
) rounds correct to two decimal places. If you want this latter behavior and assign to a variable T
the result, you can use, e.g.,
请注意不同之处, withprintf
您将获得领先的0
,而不是bc
和dc
。printf
and bc
(or dc
)之间还有另一个区别:printf
四舍五入到最接近的数字到小数点后两位,而bc
(or dc
) 将正确四舍五入到小数点后两位。如果您想要后一种行为并将结果分配给变量T
,您可以使用,例如,
T=$(dc <<< "2 k $(date +%N) 1000000000 / p")
or, if you also want the leading 0
:
或者,如果您还想要领先0
:
T=0.$(dc <<< "2 k $(date +%N) 1000000000 / p")
回答by Saurabh
Below can be done for 2 decimal precision ,
下面可以做 2 个小数精度,
echo $T | bc -l | xargs printf "%.2f"
回答by Malcolm Boekhoff
"bc" and "dc" both truncate rather than round, so nowadays I prefer Perl
"bc" 和 "dc" 都截断而不是圆角,所以现在我更喜欢 Perl
If "N" has your number of hundreths of seconds in it then:
如果“N”中有你的百分之几秒,那么:
$ perl -e "printf('%.2f', $N/100)"
I was never a Perl supporter but it is now ubiquitous and I have finally been swayed to using it instead of sed/awk etc.
我从来都不是 Perl 的支持者,但它现在无处不在,我终于习惯了使用它而不是 sed/awk 等。