[英]trying to convert a string to a decimal for iOS 13
我有一個應用程序,它在 iOS 13 之前一切正常。我檢查了一些帖子,但他們似乎在說我已經做過的事情。
我正在傳遞一個包含貨幣符號和格式的字符串,我想去掉它並使用字符串值。
func changeCurrencyToDecimal(stringNumber:String) -> Decimal {
let numberFormatter = NumberFormatter()
// Pull apart the components of the user's locale
var locComps = Locale.components(fromIdentifier: Locale.current.identifier)
// Set the specific currency code
locComps[NSLocale.Key.currencyCode.rawValue] = options?.currencyCode // or any other specific currency code
// Get the updated locale identifier
let locId = Locale.identifier(fromComponents: locComps)
// Get the new custom locale
//numberFormatter.locale = Locale(identifier: locId)
if(options?.currencyCode == nil) {
print("There is no currency code so use the default locale")
numberFormatter.locale = Locale.current
}
else{
print("We have a currency code!")
numberFormatter.locale = Locale(identifier: locId)
}
numberFormatter.numberStyle = .currency
numberFormatter.currencySymbol = ""
numberFormatter.decimalSeparator = ","
print("\(stringNumber) is the number being passed")
let number = numberFormatter.number(from: stringNumber)
// check to see if the number is nil and if so, return 0.
print("\(number) is the number converted")
if number == nil{
return 0
}
else{
print("\(number!) is the number")
let amount = number?.decimalValue
return amount!
}
}
我傳遞的字符串示例:$300.00 $ 總是觸發返回 nil。 如果我通過 300.00,那么轉換器就可以正常工作。 但我需要能夠檢查用戶為其設備設置的任何貨幣。
我正在檢查的貨幣代碼是 Apple 在var currencyCode: String? { get }
var currencyCode: String? { get }
options 就是我存儲這些代碼的地方。
numberFormatter 每次都產生 nil ,這似乎是因為我的小數沒有被剝奪其格式。
這在 iOS 13 之前再次起作用,所以我猜蘋果方面發生了一些變化,我可能還沒有遇到過。
更新這是一個用戶seniaro。 用戶輸入金額。 如果用戶立即點擊保存,我會將金額轉換為小數以保存在 coredata 中。 但是,如果用戶關閉鍵盤,我會獲取該金額並將其轉換為字符串以顯示貨幣符號。 我允許用戶設置他們的貨幣,所以使用區域設置對我不起作用,因為有時他們不使用該系統。 因此,在關閉鍵盤並以正確的格式顯示其數量后,我對其進行了編程,如果他們碰巧改變了數量並再次關閉鍵盤,並重復相同的步驟。 貨幣符號被剝離,字符串被轉換為小數。
我希望這能更好地讓您了解它在我的應用程序中的工作原理。
更新我添加了一個 if/else 語句來查看語言環境是否已設置或者是否返回 nil,如果是,則將其設置為 Locale.current
假設輸入字符串使用設備的當前語言環境,您可以使用numberStyle
創建NumberFormatter
並將Locale.current
設置為貨幣。
我用一個小操場來測試它:
import Foundation
func changeCurrencyToDecimal(_ stringNumber: String) -> Decimal? {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
let number = numberFormatter.number(from: stringNumber)
return number?.decimalValue
}
let numbersFormatted = ["$300", "$3,000.04", "3.000,04", "Wazaa", "3000000"]
numbersFormatted
.map { changeCurrencyToDecimal($0) }
.forEach { print($0 ?? "Not a value") }
這打印:
如果您因此一直得到nil
,則您的設備的語言環境與您在問題中使用的示例字符串編號不同(300 美元)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.