This code was inspired by this question: Number to Words
import Foundation
extension Int {
func plainEnglish (negativeSign: String = "negative") -> String {
func singleNumberName (number: Int) -> String {
switch (number) {
case 1: return "one"
case 2: return "two"
case 3: return "three"
case 4: return "four"
case 5: return "five"
case 6: return "six"
case 7: return "seven"
case 8: return "eight"
case 9: return "nine"
default:return ""
}
}
func tensNumberName (number: Int) -> String {
switch (number) {
case 2: return "twenty"
case 3: return "thirty"
case 4: return "fourty"
case 5: return "fifty"
case 6: return "sixty"
case 7: return "seventy"
case 8: return "eighty"
case 9: return "ninety"
default:return ""
}
}
func teensNumberName (number: Int) -> String {
switch (number) {
case 0: return "ten"
case 1: return "eleven"
case 2: return "twelve"
case 3: return "thirteen"
case 5: return "fifteen"
default:return singleNumberName(number) + "teen"
}
}
var number = self
var digits: [Int] = []
while number != 0 {
digits.append(abs(number%10))
number /= 10
}
var plainEnglish: [String] = []
var isTeen = false
let totalPlaces = digits.count
var currentPlace = 0
for (index, digit) in enumerate(digits.reverse()) {
currentPlace = totalPlaces - index
if currentPlace % 3 == 0 && digit > 0 {
plainEnglish.append(singleNumberName(digit) + " hundred")
} else if (currentPlace + 1) % 3 == 0 {
if digit == 1 {
isTeen = true
continue;
} else {
isTeen = false
plainEnglish.append(tensNumberName(digit))
}
} else {
if isTeen {
plainEnglish.append(teensNumberName(digit))
} else {
plainEnglish.append(singleNumberName(digit))
}
}
if currentPlace == 4 {
plainEnglish.append("thousand")
} else if currentPlace == 7 {
plainEnglish.append("million")
} else if currentPlace == 10 {
plainEnglish.append("billion")
}
}
let initial = (self < 0) ? negativeSign : ""
func combine (first: String, second: String) -> String {
return first + " " + second
}
let finalString = plainEnglish.reduce(initial, combine: combine)
return finalString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
This is implemented as an extension on the Int
data type, so you can use it via dot notation on any integer (including literals). Example usage:
let payamount = 98327
let dollars = payamount / 100
let cents = payamount % 100
let checkString = dollars.plainEnglish() + " dollars and " + cents.plainEnglish() + " cents"
Which results in a string that reads:
"nine hundred eighty three dollars and twenty seven cents"
negativeSign
argument for anything. Near the bottom of the function (let initial = …
), you just have a hard-coded"negative"
. (By the waynegativePrefix
might be a more precise name for the argument) \$\endgroup\$let finalString ...
line. I messed it up when I moved it out of there. \$\endgroup\$