# Increment decimal values to next integer value

I want to increment the decimal value to next integer value through shell script.

For example:

``````i=**1.6**     then I need to print i=**2**
i=**1.00001** then I need to print i=**2**
i=**1.00049** then also I need to print the value as i=**2**
``````

So what ever the case, if the decimal value is greater than even by .00000001 I need to print the value as 2.

Your question is a bit ambiguous. If you want the next integer, whatever the decimal part, below is an answer with `sh`:

``````echo \$((\${i%.*} + 1))
``````

If you want the next integer if the decimal part is more than 0, here is an answer with `sh`:

``````[ -n "\${i##*.*[1-9]*}" ]
echo \$(( \${i%.*} + \$? ))
``````

(the first test exits with 1 if `i` has some digit other than 0 after the decimal point, else it exits with 0; `\$?` contains the exit value)

Same idea with `bash` which is a bit more readable IMHO:

``````[[ "\$i" != *.*[1-9]* ]]
echo \$(( \${i%.*} + \$? ))
``````

Using POSIX `expr`, thus compatible with any shell:

``````expr "\${i%.*}" + \( "\${i##*.*[1-9]*}" = "" \)
``````
• Will fail if `i == 1.0000000`. Aug 14, 2017 at 16:54
• @DopeGhoti Why? Next integer is 2. Aug 14, 2017 at 16:57
• OP wants to increment only if the value is greater than the integer part. 1.000000 becomes 1; 1.000001 becomes 2. Aug 14, 2017 at 16:57
• From the OP: "if the decimal value is greater than even by .00000001" Aug 14, 2017 at 17:16
• @roaima The question is ambiguous. I will come up with something else. Aug 14, 2017 at 17:16

Through `awk` and add `0.5` to the result then `.f` will round it up to nearest number by itself.

``````awk -F\= 'BEGIN{printf("%.f\n", \$2+0.5)}'
``````
• Consider you have 1.01, this must be rounded up to 2. Your code doesn't do that. Aug 14, 2017 at 17:07
• Yes, it does the same Aug 14, 2017 at 17:09
• With `i=1.01` how are you using your code? The `BEGIN { }` block is being run before `awk` reads from stdin so you must be calling it in some other way. Aug 14, 2017 at 17:14
• Your `awk -F= '\$2 !~ /[\.0]+\$/{printf( "%.0f\n", \$2 + 0.5);next} {print \$2}'` fails with `i=1` (apparently it's supposed to remain `1`) Aug 14, 2017 at 17:15
• please see updated in history. BTW OP didn't mention it : ) so I did rollback until OP clarified if s/he needs it, thanks Aug 14, 2017 at 17:32
``````if [[ '1' -eq "\$(echo "\$i > \${i%.*}" | bc)" ]]; then
i=\$((\${i%.*}+1))
else
i=\${i%.*}
fi
``````

Assuming bash.

To process an arbitrary amount of decimals we either need a program that allow arbitrary precision like `bc`:

``````\$ round(){ bc <<< "a=\$1"'; scale=0; b=a/1; if (a==b) a else b+1'; }
\$ for i do round "\$i"; done
1.0000
2
2
2
``````

Or process as text:

``````\$ round(){ reg='^([0-9]*)\.0*[1-9]'; [[ \$1 =~ \$reg ]] && echo "\$((\${1%%.*}+1))" || echo "\$1"; }
\$ set 1.0000 1.6 1.00001 1.00049
\$ for i do round "\$i"; done
1.0000
2
2
2
``````