【问题标题】:Converting String to Double not working for bigger values in Swift将 String 转换为 Double 不适用于 Swift 中的更大值
【发布时间】:2020-07-28 13:59:33
【问题描述】:

我只是想将 String 转换为 Double 。这是我为此使用的功能:

private func calculateListPrice(index: Int) -> Double {
    var price = Double(0.0)
    for wish in self.dataSourceArray[index].wishes {
        var priceTrimmed = wish.price.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
        priceTrimmed = priceTrimmed.replacingOccurrences(of: ",", with: ".")
        print(priceTrimmed)
        if let doublePrice = Double(priceTrimmed) {
            price += doublePrice
            // return value * 100 so updateAmount calculates correct Int Value
        }
    }
    let rounded = Double(round(100*price)/100)
    print(rounded)
    return rounded
}

问题是这不适用于每个数字。这是一个免费的例子:

没有:999.999.99

是:2.22

是:505.05

是:31.11

否:3.111.50

是的:999.99

没有:2.000.00

【问题讨论】:

  • 对您来说“999.999.99”意味着什么? 999999.99 ? (99后的“单位”)?您是在寻找 NumberFormatter 吗?
  • @Larme 不确定,以前从未使用过,但我的意思是 999999.99
  • replacingOccurrences(of: ",", with: ".") 如果 ',' 是千位分隔符,则不要这样做。
  • @JoakimDanielson 我该怎么做?
  • 查看@zrzka 的评论,但当然要改用NumberFormatter

标签: ios swift string double


【解决方案1】:

您可以通过将其样式设置为货币类型来使用数字格式化程序。我已经实现了一个示例如下:-

let formatter = NumberFormatter()
let frenchFormat = Locale(identifier: "fr_FR")
let germanFormat = Locale(identifier: "de_DE")

formatter.numberStyle = .currency

formatter.locale = frenchFormat

if let frenchPriceValue = formatter.number(from: "100,96€"){
    print(frenchPriceValue) //Output is:- 100.96
}

formatter.locale = germanFormat
if let germanPriceValue = formatter.number(from: "123,33€"){
   print(germanPriceValue)//Output is:- 123.33
}

【讨论】:

    【解决方案2】:

    您可能应该使用NumberFormatter,因为它支持解析货币(就像您尝试做的那样),并且比使用手动方法更容易且不太可能破坏。

    因此,例如,如果您想解析货币,使用当前用户的语言环境,您可以使用:

    func priceToDouble(price: String) -> Double? {
        let currencyFormatter = NumberFormatter()
        currencyFormatter.usesGroupingSeparator = true
        currencyFormatter.numberStyle = .currency
        currencyFormatter.locale = Locale.current
        
        guard let result = currencyFormatter.number(from: price) else { return nil }
        return Double(result)
    }
    

    它将根据语言环境解析货币金额,例如,如果用户的语言环境设置为美国,它会将“$1,234.56”转换为 Double(1234.56)。如果用户的语言环境是欧洲,它会将 "€2.345,60" 转换为 Double(2345.6)

    您也可以手动设置区域设置,因此,将currencyFormatter.locale = Locale.current 替换为currencyFormatter.locale = Locale(identifier: "eu") 将使其始终使用欧洲货币格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2013-05-02
      相关资源
      最近更新 更多