Floating-point division in bash

前端 未结 4 2022
隐瞒了意图╮
隐瞒了意图╮ 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:36

    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.

提交回复
热议问题