Floating-point division in bash

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

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 15:32

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题