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

4

9

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;
Infract answered 29/6, 2015 at 20:22 Comment(2)
I'm not sure why, but I think if you divide the number by 1 then it will scale the number. echo "scale = 3; $a / 1" | bc -lPrecautionary
@ooga, sorry, it does not work.Infract
S
11

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

?

Scopolamine answered 29/6, 2015 at 20:39 Comment(0)
N
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"
Nila answered 23/4, 2021 at 18:26 Comment(0)
E
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.

Erlandson answered 29/6, 2015 at 20:24 Comment(1)
It works fine for this string. But how to implement it if I take the string as input? You can see this what I am trying to do. Thanks.Infract
O
0

I think there's two simple solutions:

read input 
var=$(echo "scale=4; $input" | bc) 
printf "%.3f\n" "$var"

and the second one is simpler:

printf "%.3f" $(cat - |bc -l)

where

cat - reads numeric value from input.

| pipes the input to the next command.

bc -l performs needed calculations.

(...) captures the output.

printf "%.3f" formats and prints the captured output as a floating-point number with three decimal places.

Oxblood answered 22/10, 2023 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.