Floating-point division in bash

孤者浪人 提交于 2019-12-04 06:25:20

问题


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)


回答1:


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.




回答2:


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



回答3:


Bash itself could not process floats.

It can, however, printf them:

$ printf 'value: %06.2f\n' 23.45
value: 023.45

So, you need an external program to do the math:

$ echo "scale=4;2345/100*20/100" | bc
4.6900

Or, equivalent:

$ bc <<<"scale=4;2345*20/10^4"
4.6900

Then, you can format the float with printf:

$ printf 'result: %06.2f\n' $(bc <<<"scale=4;2345*20/10^4")
result: 004.69

Or you can use a program that can process floats; like awk.




回答4:


How about this:

read -p "What is the total cost? " input
percent=20
echo "scale=2; $input / 100 * $percent / 100" | bc

# input = 2345 , output = 4.69


来源:https://stackoverflow.com/questions/42798095/floating-point-division-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!