Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display number to two decimal places in bash function

Tags:

linux

bash

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
like image 827
Neilos Avatar asked Nov 29 '12 18:11

Neilos


People also ask

How do you display upto 2 decimal places?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

Can Bash handle decimals?

The standard calculation Bash programming idiom ($[]) is unable to provide a decimal output.

How do you round to 3 decimal places in Bash?

$(command) is 'command substitution', it runs the command, captures its output and inserts it into the command line that contains the $(…) bc -l is calculating the expression and giving the result upto 20 decimal places printf %. 3f is taking floating number where . 3 tells it to round the number to 3 decimal places.


2 Answers

Below can be done for 2 decimal precision ,

echo $T | bc -l | xargs printf "%.2f"
like image 118
Saurabh Avatar answered Oct 16 '22 08:10

Saurabh


Bash has a printf function built in:

printf "%0.2f\n" $T
like image 39
Alex Howansky Avatar answered Oct 16 '22 08:10

Alex Howansky