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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:55:19  来源:igfitidea点击:

How to display number to two decimal places in bash function

linuxbash

提问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 +%Nby 1000000000, rounds the result to two decimal places and assigns the result to the variable T.

下面对date +%Nby的输出进行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 bcand 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 printfyou'll have the leading 0, not with bcand dc. There's another difference between printfand bc(or dc): printfrounds 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 Tthe result, you can use, e.g.,

请注意不同之处, withprintf您将获得领先的0,而不是bcdcprintfand 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 等。