简体   繁体   中英

How to convert number to words in swift by using func

Given the integer 'number' in the range of 0..<< 1000, print the number as a word. For example, given: let number: Int = 125 output should be one-hundred and twenty-five

You can use NumberFormatter pretty effectively:) Here's example

let numberFormatter = NumberFormatter()
let number = 12355532
numberFormatter.numberStyle = .spellOut
let numberAsWord = numberFormatter.string(from: NSNumber(value: number))
print(numberAsWord)

You could also extend NSNumber to do this behind the scenes like this

public extension NSNumber {
    var spelledOut: String? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return formatter.string(from: self)
    }
}

To avoid creating a Number Formatter every time you call this property you can create a static formatter. You can also make the computed property generic to support all numeric types:

extension NumberFormatter {
    static let spelled: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return formatter
    }()
}

extension Numeric {
    var spelledOut: String? { NumberFormatter.spelled.string(for: self) }
}

let integer = 1234
let integerSpelled = integer.spelledOut  // "one thousand two hundred thirty-four"

let double = 123.4
let doubleSpelled = double.spelledOut  // "one hundred twenty-three point four"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM