Friday, October 7, 2022

[SOLVED] How to output float result?

Issue

I am working on bash script: need to evaluate an input and then output the result as a float *.xxx:

I do:

read var1
var2=$((var1))
#echo $var2
echo $((var1))

input: 5+50*3/20 + (19*2)/7

my output is 17 but it should be 17.929

How to evaluate it as a float?


Solution

Bash only supports integer arithmetic.

In your case, you can use bc(1).

read var1
var2="$(bc <<<"scale=2;$var1")"

Use the scale variable in bc(1) to set the number of significant digits (default with is 0).

bc(1) is subject to truncation errors (truncation happens at every step).

Another option is to use calc(1) (if it is available on your system):

var2=$(calc -d "_=config(\"display\", 3);$var1")


Answered By - Simon Doppler
Answer Checked By - Cary Denson (WPSolving Admin)