简体   繁体   中英

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.

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 .

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),

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, eg,

T=$(dc <<< "2 k $(date +%N) 1000000000 / p")

or, if you also want the leading 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

If "N" has your number of hundreths of seconds in it then:

$ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM