Floating-point division in bash

前端 未结 4 2024
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 14:42

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 15:24

    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.

提交回复
热议问题