awkintegerdivision

Integer division in awk


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].


Solution

  • 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