-
-
Save StevenACoffman/51bba27373c8563c2e57ed68a8229a5c to your computer and use it in GitHub Desktop.
Simple algorithm for converting numbers to English words (Golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
var ( | |
ones = []string{ | |
"zero", "one", "two", "three", "four", | |
"five", "six", "seven", "eight", "nine", | |
"ten", "eleven", "twelve", "thirteen", "fourteen", | |
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen", | |
} | |
tens = []string{ | |
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", | |
} | |
big = []string{ | |
"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", | |
} | |
) | |
func num2words(number int) string { | |
out := "" | |
if number == 0 { | |
return ones[0] | |
} else if number < 0 { | |
out += "minus" | |
number = number * -1 | |
} | |
// Divide the number into groups of 3. | |
// eg: 9876543210 = [210 543 876 9] (should be read in reverse) | |
groups := []int{} | |
for { | |
if number < 1 { | |
break | |
} | |
groups = append(groups, number%1000) | |
number /= 1000 | |
} | |
ln := len(groups) - 1 | |
for i := ln; i >= 0; i-- { | |
n := groups[i] | |
if n == 0 { | |
continue | |
} | |
num := n | |
if v := num / 100; v != 0 { | |
out += " " + ones[v] + " hundred" | |
num = num % 100 | |
} | |
if v := num / 10; num >= 20 && v != 0 { | |
out += " " + tens[v] | |
num = num % 10 | |
} | |
if num > 0 { | |
out += " " + ones[num] | |
} | |
if i > 0 && i <= len(big) { | |
out += " " + big[i] + "," | |
} | |
} | |
return out[1:] | |
} | |
func main() { | |
fmt.Println(num2words(0)) | |
fmt.Println(num2words(11)) | |
fmt.Println(num2words(123)) | |
fmt.Println(num2words(999)) | |
fmt.Println(num2words(123999)) | |
fmt.Println(num2words(987654321000000009)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment