Skip to content

Instantly share code, notes, and snippets.

@Zhwt
Created June 4, 2024 02:23
Show Gist options
  • Save Zhwt/89d6f3b53a4f15fc5751e70c249d35d1 to your computer and use it in GitHub Desktop.
Save Zhwt/89d6f3b53a4f15fc5751e70c249d35d1 to your computer and use it in GitHub Desktop.
Convert number to English words in bash
#!/bin/bash
number_to_words() {
num=$1
if [ "$num" -eq 0 ]; then
echo "zero"
return 0
fi
if [ "$num" -lt 0 ]; then
echo -n "minus "
num=$(( -num ))
fi
ones=("zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen")
tens=("" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety")
scales=("" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion")
to_words_under_1000() {
n=$1
result=""
if [ "$n" -ge 100 ]; then
result+="${ones[$(( n / 100 ))]} hundred"
n=$(( n % 100 ))
[ "$n" -ne 0 ] && result+=" and "
fi
if [ "$n" -ge 20 ]; then
result+="${tens[$(( n / 10 ))]}"
n=$(( n % 10 ))
[ "$n" -ne 0 ] && result+="-${ones[$n]}"
elif [ "$n" -gt 0 ]; then
result+="${ones[$n]}"
fi
echo "$result"
}
parts=()
scale_index=0
while [ "$num" -gt 0 ]; do
part=$(( num % 1000 ))
if [ "$part" -ne 0 ]; then
words=$(to_words_under_1000 "$part")
[ "$scale_index" -ne 0 ] && words="$words ${scales[$scale_index]}"
parts=("$words" "${parts[@]}")
fi
num=$(( num / 1000 ))
scale_index=$(( scale_index + 1 ))
done
echo "${parts[*]}"
}
number_to_words 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment