How to display number to two decimal places in bash function

前端 未结 4 1558
南方客
南方客 2021-02-20 16:27

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\

4条回答
  •  面向向阳花
    2021-02-20 17:01

    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, e.g.,

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

提交回复
热议问题