1

In linux bash, I want to get the next integer for a given number only if it is a floating point number. I tried with

count=$((${count%.*} + 1));

But with the above code, all the time (even if the number is not floating point), it is giving next integer.

Expected result :

345.56 => 346
345.12 => 346
345 => 345

Can anyone help me to find the solution?

Thanks in advance.

Jenz
  • 8,280
  • 7
  • 44
  • 77

3 Answers3

0

you can use

NUMBER=365
perl -w -e "use POSIX; print ceil($NUMBER/1.0), qq{\n}"

for assigning to a variable

MYVAR=$(perl -w -e "use POSIX; print ceil($NUMBER/1.0), qq{\n}")
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • I am sorry I misread Expected output. I changed my code. BTW downvoting to this answer is littlebit odd. You used this approach in the end. Please at least accept it as answer so that others can also use it. thank you – Derviş Kayımbaşıoğlu Jan 31 '19 at 14:29
  • @Simonare .. Thank you. Its working for me. Without printing how can I assign the value to a variable? – Jenz Jan 31 '19 at 14:33
  • A little longer than necessary. Just `num=$(perl -e "use POSIX; print ceil($num)")` would also work. – Socowi Jan 31 '19 at 14:47
  • Works for me with `perl v5.26.1` on Ubuntu 18.04. What is exactly is the problem? Do you get an error or an output different from 366? – Socowi Jan 31 '19 at 15:45
0

In awk. Some test records:

$ cat file    # dont worry about stuff after =>
345.56 => 346
345.12 => 346
345 => 345
345.0
0 
-345.56 => 346
-345.12 => 346
-345 => 345
-345.0

The awk:

$ awk '{print $1 " => " int($1)+($1!=int($1)&&$1>0)}' file
345.56 => 346
345.12 => 346
345 => 345
345.0 => 345
0 => 0
-345.56 => -345
-345.12 => -345
-345 => -345
-345.0 => -345
James Brown
  • 36,089
  • 7
  • 43
  • 59
0

You'll have to test for the presence of a dot:

case $count in
    *.*) count=$(( ${count%.*} + 1 )) ;;
      *) : nothing to do
         ;;
esac

or

[[ $count == *.* ]] && count=$(( ${count%.*} + 1 ))
glenn jackman
  • 238,783
  • 38
  • 220
  • 352