Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active September 18, 2017 12:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scotteg/230f8677e4b9da5bb98f to your computer and use it in GitHub Desktop.
Save scotteg/230f8677e4b9da5bb98f to your computer and use it in GitHub Desktop.
Converts any number (e.g., 1) or a number string (e.g., "1") into a spelled-out number string (e.g., "one").
import Foundation
/**
Converts any numeric literal (e.g., 1) or string containing a numeric literal (e.g., "1"), into a spelled-out number string (e.g., "one"). [Source on GitHub](http://bit.ly/SwiftSpellOutNumber)
- parameter number: a numeric literal, or string containing a numeric literal
- returns: String?
*/
public func spellOut<N>(number: N) -> String? {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
switch number {
case is Int, is UInt, is Float, is Double:
return formatter.string(from: number as! NSNumber)
case is String:
if let number = Double((number as! String)) {
return formatter.string(from: NSNumber(floatLiteral: number))
}
default:
break
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment