Skip to content

Instantly share code, notes, and snippets.

@yycking
Created July 19, 2021 08:13
Show Gist options
  • Save yycking/94c6db4d23341aebcefbece30cacf5d9 to your computer and use it in GitHub Desktop.
Save yycking/94c6db4d23341aebcefbece30cacf5d9 to your computer and use it in GitHub Desktop.
數字轉中文大寫(最大單位只能換到萬)
extension String {
subscript(_ i: Int) -> String {
let idx1 = index(startIndex, offsetBy: i)
let idx2 = index(idx1, offsetBy: 1)
return String(self[idx1..<idx2])
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[start ..< end])
}
subscript (r: CountableClosedRange<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return String(self[startIndex...endIndex])
}
}
let number = "10".reversed()
let symbol = [
"","拾", "佰", "仟", "萬"
]
let chinese = "零壹貳參肆伍陸柒捌玖"
var result = number.map { (char) -> String in
let index = Int(String(char))
return chinese[index ?? 0]
}
for i in 1 ..< result.count {
if result[i] == "零" {
if result[i-1] == "零" {
result[i-1] = ""
}
}else {
result[i] += symbol[i]
}
}
var text = result.reversed().joined()
if text.count > 1, text.hasSuffix("零") {
text.removeLast()
}
print(text)
@yycking
Copy link
Author

yycking commented Aug 9, 2022

另一種寫法
原生spell為小寫,需轉大寫

let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "zh_TW")
let result = formatter.string(from: number)?
    .map { value -> String in
        switch value {
        case "一": return"壹"
        case "二": return"貳"
        case "三": return"參"
        case "四": return"肆"
        case "五": return"伍"
        case "六": return"陸"
        case "七": return"柒"
        case "八": return"捌"
        case "九": return"玖"
        case "十": return"拾"
        case "百": return"佰"
        case "千": return"仟"
        default: return "\(value)"
        }
    }.joined()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment