0

I'm ALL NEW in shell script , hence have a question about how to round up integer.

Here is a line of the code from a script by keke(smstools3 developer)

  balance=$(substr "$result" "$balance_prefix" "$balance_suffix")

And my balance is 111.12 , and I wish to round it up.

I tried

    balance1=$(substr "$result" "$balance_prefix" "$balance_suffix")
    balance=$("%0.f\n" "$balance1")

or

    balance1=$(substr "$result" "$balance_prefix" "$balance_suffix")
    balance=$(ceil($balance1))

Both refer from some answers after google it , I not even know if the syntax is correct.And of course both example return blank.

Any hints or advice?Thank you.

Edit:

# Check that required words exists:
if [[ "$result" == *${balance_prefix}* ]] && \
   [[ "$result" == *${balance_suffix}* ]]
then
  # Get the balance and check it:
  balance=$(substr "$result" "$balance_prefix" "$balance_suffix")
  balance_low=0

  if [ $(expr "$balance" + 1 2> /dev/null) ]; then
    [ $balance -le $alert_balance ] && balance_low=1
  else
    echo "Error while parsing an integer: $balance"
  fi
else
  echo "Error while parsing the answer (balance): $result"
fi

source : http://smstools3.kekekasvi.com/topic.php?id=320

Irene Ling
  • 1,881
  • 3
  • 26
  • 41
  • What do you want to round it up to? Could you add a couple of more input/output examples to make it clearer please? – hendry Feb 01 '12 at 07:02
  • @hendry Thank for your reply.Because in the script if my balance is decimal value it won't do any comparison(eg. if balance lower than 20 then send an alert message) I paste more codes in my question. – Irene Ling Feb 01 '12 at 07:05
  • I think the code is distracting to the "rounding up problem" here. Perhaps http://stackoverflow.com/a/2395601/4534 solves the problem. – hendry Feb 01 '12 at 07:08

2 Answers2

2
balance=`python -c  "from math import ceil; print(ceil($balance1))"`

or

balance=`perl -MPOSIX -e "print ceil($balance1)"`
kev
  • 155,172
  • 47
  • 273
  • 272
1

Using only a minimum of standard tools (perl and python are quite common though):

balance=$(echo "x=${balance1}; scale=0; xx=x/1; if(x>xx) xx+=1; print xx"|bc -l)

Hannes
  • 474
  • 2
  • 4