微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用货币如何简化 String 到 Decimal 的这种转换?

如何解决使用货币如何简化 String 到 Decimal 的这种转换?

我正在 Swift 中处理货币。我需要将字符串转换为十进制。我认为我已经解决了几个问题:

  • 十进制类型使用“.”,但有些语言环境使用“,”
  • 用户可能会错误地输入额外的额外数字(因此在我的示例代码中为“2500,12345”)
  • 并非所有货币都有 2 个小数位,有些货币有 0 或 3

但问题是:

如何简化这段代码

正如你在代码中看到的,我在 String 和 NSDecimal 之间来回移动以解决上述问题。我认为可能有一种更简单的方法。我希望我可以告诉 Swift 在第一次从 String 到 Decimal 的转换过程中减少不必要的分数。以某种方式使用 currencyFormatter.maximumFractionDigits。但是当我打印 currencyFormatter.maximumFractionDigits 的值时,它只有在 currencyFormatter.numberStyle = .currency

之后才具有正确的值(如果是美元,则为 2)

有什么想法吗? :)

import Foundation

let amountString = "2500,12345"
var amountDecimal: Decimal = 0
var finalDecimal: Decimal = 0
print("amountString (\(type(of: amountString))):",amountString)

let currencyFormatter = NumberFormatter()
// Set locale to Polish,where decimal separator is "," instead of "."
currencyFormatter.locale = Locale(identifier: "pl_PL")
currencyFormatter.numberStyle = .decimal

// Convert String to Decimal and change,to .
if let number = currencyFormatter.number(from: amountString) {
    amountDecimal = number.decimalValue
    print("amountDecimal (\(type(of: amountDecimal))):",amountDecimal)
}

// set currency to USD
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "USD"

let amountCurrency = currencyFormatter.string(for: amountDecimal)
print("amountCurrency (\(type(of: amountCurrency))):",amountCurrency ?? "0")

if let number = currencyFormatter.number(from: amountCurrency ?? "0") {
    finalDecimal = number.decimalValue
    print("finalDecimal (\(type(of: finalDecimal))):",finalDecimal)
}

编辑: 到目前为止,这是针对 iOS 应用的,用户将使用 TextField 提供字符串,键盘设置为带小数的数字。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。