如何将双格式转换成货币 - 斯威夫特3

问题描述 投票:31回答:7

我是新来的斯威夫特编程和我已经建立在Xcode 8.2一个简单的小费计算器应用程序,我有我的计算,建立了我的IBAction内下方。但当我实际运行我的应用程序和输入量来计算(如23.45),它有超过2位小数出现。我如何格式化它在这种情况下.currency

@IBAction func calculateButtonTapped(_ sender: Any) {

    var tipPercentage: Double {

        if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
            return 0.05
        } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
            return 0.10
        } else {
            return 0.2
        }
    }

    let billAmount: Double? = Double(userInputTextField.text!)

    if let billAmount = billAmount {
        let tipAmount = billAmount * tipPercentage
        let totalBillAmount = billAmount + tipAmount

        tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
        totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
    }
}
ios swift formatting currency
7个回答
73
投票

如果你想迫使货币$您可以使用此字符串初始化:

String(format: "Tip Amount: $%.02f", tipAmount)

如果你希望它是完全依赖于设备的区域设置,你应该使用NumberFormatter。这将考虑到小数位的货币的数量,以及正确定位的货币符号。例如。双值2.4将返回“2,40€”为es_ES本地化和“¥2”为jp_JP语言环境。

let formatter = NumberFormatter()
formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already
formatter.numberStyle = .currency
if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) {
    tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)"
}

9
投票

要做到这一点,最好的方法是创建一个NSNumberFormatter。 (斯威夫特3 NumberFormatter)你可以要求货币,它会建立字符串按照用户的本地化设置,这是非常有用的。

如果你想迫使美国格式的美元和美分字符串可以格式化它这种方式:

let amount: Double = 123.45

let amountString = String(format: "$%.02f", amount)

9
投票

除了被别人讨论的NumberFormatterString(format:),你可能要考虑使用DecimalNSDecimalNumber和控制四舍五入自己,从而避免浮点运算的问题。如果你正在做一个简单的小费计算器,这可能是没有必要的。但是,如果你正在做的事情就像在一天的末尾添加了提示,如果你不圆的数量和/或使用十进制数做你的数学,你可能会导致错误。

因此,继续和配置格式:

let formatter: NumberFormatter = {
    let _formatter = NumberFormatter()
    _formatter.numberStyle = .decimal
    _formatter.minimumFractionDigits = 2
    _formatter.maximumFractionDigits = 2
    _formatter.generatesDecimalNumbers = true
    return _formatter
}()

然后,用十进制数:

let string = "2.03"
let tipRate = Decimal(sign: .plus, exponent: -3, significand: 125) // 12.5%
guard let billAmount = formatter.number(from: string) as? Decimal else { return }
let tip = (billAmount * tipRate).rounded(2)

guard let output = formatter.string(from: tip as NSDecimalNumber) else { return }
print("\(output)")

哪里

extension Decimal {

    /// Round `Decimal` number to certain number of decimal places.
    ///
    /// - Parameters:
    ///   - scale: How many decimal places.
    ///   - roundingMode: How should number be rounded. Defaults to `.plain`.
    /// - Returns: The new rounded number.

    func rounded(_ scale: Int, roundingMode: RoundingMode = .plain) -> Decimal {
        var value = self
        var result: Decimal = 0
        NSDecimalRound(&result, &value, scale, roundingMode)
        return result
    }
}

很明显,你可以代替所有上述“2个小数位”引用与任何数量的适合你使用(或可能使用变量的小数位的数量)的货币。


9
投票

如何做到这一点在斯威夫特4:

let myDouble = 9999.99
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current

// We'll force unwrap with the !, if you've got defined data you may need more error checking

let priceString = currencyFormatter.string(from: NSNumber(value: myDouble))!
print(priceString) // Displays $9,999.99 in the US locale

7
投票

你可以创建一个字符串或诠释的延伸,我会表现出与字符串的例子

extension String{
     func toCurrencyFormat() -> String {
        if let intValue = Int(self){
           let numberFormatter = NumberFormatter()
           numberFormatter.locale = Locale(identifier: "ig_NG")/* Using Nigeria's Naira here or you can use Locale.current to get current locale, please change to your locale, link below to get all locale identifier.*/ 
           numberFormatter.numberStyle = NumberFormatter.Style.currency
           return numberFormatter.string(from: NSNumber(value: intValue)) ?? ""
      }
    return ""
  }
}

link to get all locale identifier


5
投票

你可以转换这样的:本功能转换为保持你maximumFractionDigits只要你想做的事

static func df2so(_ price: Double) -> String{
        let numberFormatter = NumberFormatter()
        numberFormatter.groupingSeparator = ","
        numberFormatter.groupingSize = 3
        numberFormatter.usesGroupingSeparator = true
        numberFormatter.decimalSeparator = "."
        numberFormatter.numberStyle = .decimal
        numberFormatter.maximumFractionDigits = 2
        return numberFormatter.string(from: price as NSNumber)!
    } 

我在课堂上示范创建它,然后当你打电话,你能接受它的另一个类,如下

 print("InitData: result convert string " + Model.df2so(1008977.72))
//InitData: result convert string "1,008,977.72"

0
投票
extension Float {
    var localeCurrency: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = .current
        return formatter.string(from: self as NSNumber)!
    }
}
    amount = 200.02
    print("Amount Saved Value ",String(format:"%.2f", amountSaving. localeCurrency))

对我来说,它的回报率0.00!访问它返回时0.00在我看来Extenstion完美!为什么?


-2
投票

这是如何做:

    let currentLocale = Locale.current
    let currencySymbol = currentLocale.currencySymbol
    let outputString = "\(currencySymbol)\(String(format: "%.2f", totalBillAmount))"

第一行:你获取当前的语言环境

2号线:你得到了该区域的CURRENCYSYMBOL。 ($,£等)

第三行:使用格式初始化截断你的双到小数点后2位。

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