当前位置: 首页 > 面试题库 >

如何将Double格式化为Currency-Swift 3

景德海
2023-03-14
问题内容

我是Swift编程的新手,我一直在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)"
    }
}

问题答案:

如果要将货币强制为$,可以使用此字符串初始化程序:

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

如果希望它完全取决于设备的语言环境设置,则应使用NumberFormatter。这将考虑到货币的小数位数以及正确放置货币符号。例如,双精度值2.4将为es_ES语言环境返回“
2,40€”,为jp_JP语言环境返回“¥2”。

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)"
}


 类似资料:
  • 问题内容: 如何格式化双精度字符为字符串,并在整数和小数部分之间加点​​? 以上格式仅带有逗号:“,”。 问题答案: 正在使用JVM的默认语言环境。您可以使用或直接使用任何语言环境。 要么 要么 要么

  • 本文向大家介绍如何将Java LocalDateTime格式化为ISO_DATE_TIME格式,包括了如何将Java LocalDateTime格式化为ISO_DATE_TIME格式的使用技巧和注意事项,需要的朋友参考一下 首先,设置日期: 现在,将日期时间格式化为ISO_DATE_TIME格式: 示例 输出结果

  • 问题内容: 我正在实现一个接口,该接口的功能类似于可以包含某种对象的表的功能。该接口指定以下功能: 在我的实现中,我感到很困惑的是,我将表数据存储在2D 数组()中。当我需要返回值时,我想执行以下操作(假定只在包含double的列上调用,因此将没有): 但是- Java不允许强制转换为。将其强制转换为可以,因为它是一个对象,而不是基元,但是我的接口指定数据将以形式返回。 所以我有两个问题: 有什么

  • 问题内容: 我有一个名为date的LocalDate变量,当我打印它时显示1988-05-05,我需要将此变量转换为要打印为1988年5月5日。如何执行此操作? 问题答案: 如果他从Java 8中的新功能LocalDate开始,SimpleDateFormat将无法工作。从我所看到的,您将不得不使用DateTimeFormatter,http://docs.oracle.com/javase/8/

  • 我有一个LocalDate变量名为date,当我打印它时,它显示1988-05-05,我需要将它转换成05.may1988。怎么做?

  • 在生成Excel文件时,是否可以在ColdFusion代码中指定此格式?