Table of Contents
Using printf
Command
Use the printf
command to convert float to integer in bash.
1 2 3 4 5 |
float_num=3.14 int_num=$(printf "%.0f" "$float_num") echo "$int_num" |
1 2 3 |
3 |
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:
1 2 3 4 5 |
float_num=3.14 int_num=${float_num%.*} echo "$int_num" |
1 2 3 |
3 |
Using awk
Command
Use the awk
command to convert float to integer in bash.
1 2 3 4 5 |
float_num=3.14 int_num=$(awk 'BEGIN { printf "%.0f", '"$float_num"' }') echo "$int_num" |
1 2 3 |
3 |
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.
1 2 3 4 5 6 |
float_num=3.14 int_num=$(echo "$float_num" | sed 's/\..*//') echo "Float number: $float_num" echo "Integer number: $int_num" |
1 2 3 4 |
Float number: 3.14 Integer number: 3 |
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.
1 2 3 4 5 6 |
float_num=3.14 int_num=$(echo "$float_num" | cut -d '.' -f 1 | tr -d '\n') echo "Float number: $float_num" echo "Integer number: $int_num" |
1 2 3 4 |
Float number: 3.14 Integer number: 3 |
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.