Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Roundup decimal number to next whole number 4

Status
Not open for further replies.

ljsmith91

Programmer
May 28, 2003
305
US
Using Korn scripting, is there any way of rounding up a decimal number to the next highest whole non- decimal number ? Examples:

if $num = 2.2 then I want $num to = 3
if $num = 17.28 then I want $num to = 18
if $num = 1002.758 then I want $num to = 1003

Any help or direction would be great. Thanks so much.

 
The basic logic is add 1 to the number and discard the fraction. This script forces the 'num' variable to be an integer (typeset), then sets it to the input parameter ($1) plus one.

Code:
$ cat kscript
#!/usr/bin/ksh
typeset -i num
num=$(( $1 + 1 ))
echo $num
$ kscript 4.3
5
$ kscript 4.8
5
$
 
I don't mean to nitpick, but... well, actually, yes I do. :) How about the case $num = 5.0 or $num = 7?

Another way would be to split the variable into two using the . separator, and only add 1 to the first part if the second part is greater than 0.

Annihilannic.
 
Thanks...I have been removed from unix scripting for quite some time and this helps fix a need in an old script someone else wrote.
 
The script expanded to include Annihilannic's special cases:

Code:
$ cat kscript
#!/usr/bin/ksh
typeset -i num           # $num defined as integer
num=$1                   # integer portion of the input number
index=`expr index $1 .`  # position of the decimal point in the number
if [ $index -gt 0 ]      # not an integer if index is greater than zero
then
   length=`expr length $1`           # length of the number
   length2=$(( $length - $index ))   # length of the fraction
   length3=$(( $index + 1 ))         # substring start position for fraction
   fraction=`expr substr $1 $length3 $length2`
fi
if [[ $fraction -gt 0 ]] # if non-zero fraction, add 1 to the input number
  then num=$(( $1 + 1 ))
fi
echo $num
$ kscript 4
4
$ kscript 4.0
4
$ kscript 4.00001
5
$ kscript 4.3
5
$ kscript 4.8
5
$
 
test "${num#${num%.*}}" != "" && num=$(($num+1))
 
Another solution using awk:

Code:
echo $num | awk -F. '{if($2>=1){print $1+1}else{print $1}}'

Regards,
Chuck
 
And another way using case
Code:
case $num in
  *.*) num=$(($num+1)) ;;
esac
 
To fix a case where you might have e.g. 4.0
Code:
case $num in
  *.*[1-9]*) num=$(($num+1))
esac
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top