试图在iOS 13中将字符串转换为小数

问题描述 投票:0回答:1

我有一个应用程序,它在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 }选项中提供的货币代码,正是我存储这些货币的位置。

numberFormatter每次都会产生nil,这似乎是因为我的十进制数并未被删除。

同样在iOS 13之前可以使用,所以我想苹果方面已经有所改变,我可能还没有发现。

UPDATE这是用户seniaro。用户输入金额。如果用户立即点击“保存”,我将取其金额并将其转换为十进制形式以保存在coredata中。但是,如果用户关闭了键盘,我会拿走那个金额并将其转换为字符串以显示货币符号。我允许用户设置货币,因此使用语言环境对我不起作用,因为有时他们不使用该系统。因此,在关闭键盘并以正确的格式显示其数量之后,我对其进行了编程,以使它们碰巧更改其数量并再次关闭键盘,然后重复相同的步骤。除去货币符号,并将字符串转换为小数。

我希望这能使您更好地了解我的应用程序中的工作原理。

UPDATE我添加了一条if / else语句,以查看是否已设置语言环境或它返回nil,如果是,则将其设置为Locale.current。

我有一个应用程序,它在iOS 13之前都可以正常工作。我检查了几篇文章,但他们似乎在说我已经做了什么。我正在传递带有货币符号和...

ios swift nsnumberformatter
1个回答
0
投票

假设输入字符串使用设备的当前语言环境,则可以用NumberFormatter创建Locale.current并将numberStyle设置为货币。

© www.soinside.com 2019 - 2024. All rights reserved.