利用 NumberFormatter 將 7 變成 Seven

開發 iOS App 時,我們常常會依 App 的需求,將數字變成特定格式的字串,比方將 7 變成文字 Seven,或是變成金額 $7.00。

當然我們可以自己寫程式轉換,如以下例子用 dictionary 定義阿拉伯數字對應的英文。

let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ]

但是我們其實可以偷懶,因為 NumberFormatter 已經幫我們做好了 ! 將數字變成字串的工作就交給它吧。

NumberFormatter 的 numberStyle 決定轉換的格式,接下來我們就來看看常用的一些格式吧。

1 spellOut

將數字變成我們平常講的文字。

let formatter = NumberFormatter()formatter.numberStyle = .spellOutvar numberString = formatter.string(from: 7)numberString = formatter.string(from: 31)

設定語言

formatter.locale = Locale(identifier: "zh_TW")

2 currency

金錢格式。

formatter.numberStyle = .currency

設定金錢符號對應的國家。

formatter.currencyCode = "JPY"

3 ordinal

序數,數字的順序表達格式。

formatter.numberStyle = .ordinal
formatter.numberStyle = .ordinalformatter.locale = Locale(identifier: "zh_TW")

4 percent

百分比格式。

formatter.numberStyle = .percentnumberString = formatter.string(from: 0.7)numberString = formatter.string(from: 0.32)

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade