Monday, December 22, 2014

Simple Bash Function/Script to Convert Numbers to Strings e.g. 45 => Forty Five

Begin num2str.bsh :
(Thanks to logic I found somewhere on the internet in a file entitled NumberWordConverter.java - I can't recall exactly where I found it since I have since had problem with my browser and wiped the history out - I only converted it to Bash)   

#!/usr/bin/env bash

declare -a units=("" "one" "two" "three" "four" "five" "six" "seven" \
            "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" \
            "fifteen" "sixteen" "seventeen" "eighteen" "nineteen")
declare -a tens=("" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety")

function convert() {
declare -i INTEGER=$1
 if (($INTEGER < 0)); then
   echo -en "minus "
   convert $(($INTEGER*-1))
elif (($INTEGER < 20)); then
   echo -en ${units[$INTEGER]}
elif (($INTEGER < 100)); then
   echo -en ${tens[$(($INTEGER/10))]} 
   (($INTEGER%10)) && echo -en " "
   echo -en ${units[$(($INTEGER%10))]}
elif (($INTEGER < 1000)); then
   echo -en "${units[$(($INTEGER/100))]} hundred"
   (($INTEGER%100)) && echo -en " "
   convert $(($INTEGER%100))
elif (($INTEGER < 1000000)); then
   convert $(($INTEGER/1000))
   echo -en " thousand"
   (($INTEGER%1000)) && echo -en " "
   convert $(($INTEGER%1000))
elif (($INTEGER < 1000000000)); then
   convert $(($INTEGER/1000000))
   echo -en " million"
   (($INTEGER%1000)) && echo -en " "
   convert $(($INTEGER%1000000))
else
   convert $(($INTEGER/1000000000))
   echo -en " billion"
   (($INTEGER%1000000000)) && echo -en " "
   convert $(($INTEGER%1000000000))
fi
}
convert $1
echo 


$ num2str.bsh 4541
four thousand five hundred forty one
$ num2str.bsh 45414
forty five thousand four hundred fourteen
$ num2str.bsh 4541443
four million five hundred forty one thousand four hundred forty three

No comments:

Post a Comment