How to round a floating point number upto 3 digits after decimal point in bash

10,903

Solution 1

What about

a=`echo "5+50*3/20 + (19*2)/7" | bc -l`
a_rounded=`printf "%.3f" $a`
echo "a         = $a"
echo "a_rounded = $a_rounded"

which outputs

a         = 17.92857142857142857142
a_rounded = 17.929

?

Solution 2

You can use awk:

awk 'BEGIN{printf "%.3f\n", (5+50*3/20 + (19*2)/7)}'
17.929

%.3f output format will round up the number to 3 decimal points.

Solution 3

Try using this: Here bc will provide the bash the functionality of caluculator and -l will read every single one in string and finally we are printing only three decimals at end

read num
echo $num | bc -l | xargs printf "%.3f"
Share:
10,903
Enamul Hassan
Author by

Enamul Hassan

Like to have fun. If you do not like fun, then keep distance from me! Because it is better for both of us! However, I have passed my undergraduate in early 2017 in the field of Computer Science and Engineering from Shahjalal University of Science and Technology, Sylhet, Bangladesh. Later, in late 2017, I was appointed as a Lecturer in the same department. In the later part of 2019, I was promoted to Assistant Professor. I really enjoy my profession. I love my students very much. To know more about me, you can visit here. Feel free to drop your lines at: enam [hyphen] cse [at] sust [dot] edu Criticism and suggestion are appreciated!

Updated on June 05, 2022

Comments

  • Enamul Hassan
    Enamul Hassan almost 2 years

    I am a new bash learner. I want to print the result of an expression given as input having 3 digits after decimal point with rounding if needed. I can use the following code, but it does not round. Say if I give 5+50*3/20 + (19*2)/7 as input for the following code, the given output is 17.928. Actual result is 17.92857.... So, it is truncating instead of rounding. I want to round it, that means the output should be 17.929. My code:

    read a
    echo "scale = 3; $a" | bc -l
    

    Equivalent C++ code can be(in main function):

    float a = 5+50*3.0/20.0 + (19*2.0)/7.0;
    cout<<setprecision(3)<<fixed<<a<<endl;