Bash Multiplying Decimal to int

后端 未结 5 1792
花落未央
花落未央 2020-12-30 09:10

I read price from user input. When i multiply the input with int like this

T=\"$((PRICE*QTY))\"|bc; gives line 272: 12.

相关标签:
5条回答
  • 2020-12-30 09:51

    You can use mul=0.8 exp=200 texp=awk -vp=$mul -vq=$exp 'BEGIN{printf "%.2f" ,p * q}'

    Hope this is going to work.

    0 讨论(0)
  • 2020-12-30 09:52
    T="$(echo "$PRICE*$QTY" | bc)"
    
    0 讨论(0)
  • 2020-12-30 09:59

    First, trying to do floating-point arithmetic with bc(1) without using the -l flag is bound to give you some funny answers:

    sarnold@haig:~$ bc -q
    3.5 * 3.5
    12.2
    sarnold@haig:~$ bc -q -l
    3.5 * 3.5
    12.25
    

    Second, the $((...)) is an attempt to do arithmetic in your shell; neither my bash nor dash can handle floating point numbers.

    If you want to do the arithmetic in your shell, note printf(1) as well as (probably) your shell's built-in printf function. If you want to do the arithmetic in bc, note the special variable scale.

    0 讨论(0)
  • 2020-12-30 10:00

    this works:

    
    PRICE=1.1
    QTY=21
    RES=$(echo "scale=4; $PRICE*$QTY" | bc)
    echo $RES
    
    0 讨论(0)
  • 2020-12-30 10:09
    var=$(echo "scale=2;$PRICE*$QTY" |bc)
    

    You can also use awk

    awk -vp=$PRICE -vq=$QTY 'BEGIN{printf "%.2f" ,p * q}'
    
    0 讨论(0)
提交回复
热议问题