[英]How to display number to two decimal places in bash function
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 "($1/100).(${$1:${#1}-3:${#1}-1})"
}
T=$time
sleep 2
T=$dTime T
Bash具有内置的printf函数:
printf "%0.2f\n" $T
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
的输出除以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
. 注意区别,在
printf
您将以0
bc
,而不是bc
和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. printf
和bc
(或dc
)之间还有另一个区别: printf
舍入到最接近的数字到小数点后两位,而bc
(或dc
)舍入到小数点后两位。 If you want this latter behavior and assign to a variable T
the result, you can use, eg, 如果您希望这种后一种行为并将结果分配给变量
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")
下面可以完成2位小数精度,
echo $T | bc -l | xargs printf "%.2f"
"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等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.