Integer division in awk

user000001 picture user000001 · Feb 13, 2013 · Viewed 28.9k times · Source

I want to divide two numbers in awk, using integer division, i.e truncating the result. For example

k = 3 / 2
print k

should print 1

According to the manual,

Division; because all numbers in awk are floating-point numbers, the result is not rounded to an integer

Is there any workaround to get an integer value?

The reason is that I want to get the middle element of an array with integer indexes [0 to num-1].

Answer

Gilles Quenot picture Gilles Quenot · Feb 13, 2013

Use the int function to get the integer part of the result, truncated toward 0. This produces the nearest integer to the result, located between the result and 0. For example, int(3/2) is 1, int(-3/2) is -1.

Source: The AWK Manual - Numeric Functions