Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating-point division in bash

I'm trying to convert whatever numbers the user inputs into 2 decimal places. For instance

What is the total cost in cents? 2345
output: 23.45

this is the code i have so far

percentage=20 #cannot change numerical value must convert into 0.20
echo -n "What is the total cost? ";
read cost_in_cents
echo "scale 1; $cost_in_cents" | bc

I'm also going to be doing some multiplication with percentage, how can i also convert the percentage into a float (0.20)

like image 603
Bob Avatar asked Oct 27 '25 08:10

Bob


2 Answers

awk to the rescue!

you can define your own floating point calculator with awk, e.g.

$ calc() { awk "BEGIN{ printf \"%.2f\n\", $* }"; }

now you can call

$ calc 43*20/100

which will return

8.60
like image 140
karakfa Avatar answered Oct 29 '25 02:10

karakfa


Perhaps it's nostalgia for reverse polish notation desk calculators, but I'd use dc rather than bc here:

dc <<<"2 k $cost_in_cents 100 / p"

Output is, properly, a float (with two digits past the decimal point of precision).

The exact same code, with no changes whatsoever, will work to convert 20 to .20.


See BashFAQ #22 for a full discussion on floating-point math in bash.

like image 40
Charles Duffy Avatar answered Oct 29 '25 02:10

Charles Duffy