Skip to content

Instantly share code, notes, and snippets.

@piouPiouM
Created March 7, 2010 11:10
Show Gist options
  • Save piouPiouM/324313 to your computer and use it in GitHub Desktop.
Save piouPiouM/324313 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# string_to_int.sh - Shell script to convert a string or float number
# to an integer.
# @link http://pioupioum.fr/snippets/bash-convertir-string-to-integer.html
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)"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment