Convert Float to Integer in Bash

Convert Float to Integer in Bash

Using printf Command

Use the printf command to convert float to integer in bash.

First, the float_num variable is initialized with the floating-point number. Then to convert the floating-point number to an integer, the printf command is used with the format string %.0f (specifies that printf should output the floating-point number with zero decimal places).

The obtained integer value is then stored in a variable int_num using command substitution. Finally, the integer number stored in int_num is displayed on the console.

You can also use below expression:

Using awk Command

Use the awk command to convert float to integer in bash.

First, the float_num variable is initialized with the floating-point number. Then, to convert the floating point number to an integer, the awk command is used with the printf command and the format string %.0f (specifies that printf should output the floating-point number with zero decimal places).

The obtained integer value is then stored in a variable int_num using command substitution. Finally, the integer number stored in int_num is displayed on the console.

Using the sed Command

Use the sed command to convert float to integer in bash.

In the above example, we have taken a variable float_num, initialized with the floating-point number 3.14. Then, the sed command converts the floating point number to an integer.

The regular expression's/\..*//' replaced everything after the decimal point (\.) with an empty string (//). The integer part is then assigned to the variable int_num. Finally, the integer number stored in int_num is displayed on the console.

Using cut and tr Commands

Use the cut and tr commands to convert float to integer in bash.

First, we initialized the float_num variable with the floating-point number. Then, the delimiter . is used with the cut command to separate the integer and fractional parts of the floating-point number. After having the integer part, the cut command, further called the tr command, pipes the first part, integer, and deletes the newline characters.

The obtained integer value is then stored in a variable int_num using command substitution. Finally, the integer number stored in int_num is displayed on the console.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *