The notebook
Bash: convert a string to an integer
Bash can’t convert a float to an integer, but printf handles it just fine: here is a small shell function that does the job.
- Lire cet article en français
- English
Bash doesn’t offer a function to convert a string or a floating-point number to an integer.
That said, it’s not impossible: just call printf1 and you’re done!
bash
#!/usr/bin/env bash
# string_to_int.sh - Shell script to convert a string or float number
# to an integer.
function string_to_int ()
{
LANG=C
d=${1##*.}
if [[ ${#1} -eq ${#d} ]]; then
d=0
fi
e=${1%.*}
e=${e//,/}
printf %.0f "$e.$d" 2>/dev/null
}
not_int=("12.652" "-12.652" 12.652 14 "12,652" foo "1,254.8" 1,254.8 "125,160,254.8" "125,160,254")
for value in ${not_int[@]}; do
echo "Convert $value to int: $(string_to_int $value)"
doneWhich gives us:
bash
$ ./string_to_int.sh
Convert 12.652 to int: 13
Convert -12.652 to int: -13
Convert 12.652 to int: 13
Convert 14 to int: 14
Convert 12,652 to int: 12652
Convert foo to int: 0
Convert 1,254.8 to int: 1255
Convert 1,254.8 to int: 1255
Convert 125,160,254.8 to int: 125160255
Convert 125,160,254 to int: 125160254See it on GitHub.
Updated on March 7, 2010
Added support for United States (US) notation. Thanks to patpro.
Footnotes
-
the decimal separator
.has to be replaced with,before callingprintf. ↩
