Itai Ganot Itai Ganot - 3 months ago 16
Bash Question

How can I convert from a decimal to an integral numeric variable in a bash script?

I have a value which looks like this: 26.3

I want to work on that value but I need it to be integer, so is there a simple way to do that?

26.3 -> 26
44.9 -> 44



One option is to use awk:

$ var=26.3
$ awk -v v="$var" 'BEGIN{printf "%d", v}'

The %d format specifier results in only the integer part of the number being printed, rounding it down.

As Mark has mentioned in his answer, a simple substitution will fail in cases where there is no leading digit, such as .9, whereas this approach will print 0.

Rather than using a format specifier, it is also possible to use the int function in awk. The variable can be passed in on standard input rather than defining a variable to make things shorter:

$ awk '{$0=int($0)}1' <<< "44.9"

In case you're not familiar with awk, the 1 at the end is common shorthand, which always evaluates to true so awk performs the default action, which is to print the line. $0 is a variable which refers to the contents of the line.

Thanks to Jidder for the suggestion.