【问题标题】:Rounding a double to 2 decimal places in Swift, XCode 12 [duplicate]在Swift,XCode 12中将双精度舍入到小数点后2位[重复]
【发布时间】:2021-01-13 21:00:33
【问题描述】:

我有以下 Swift 代码:

var yourShare: Double {
        guard let totalRent = Double(totalRent) else { return 0 }
        guard let myMonthlyIncome = Double(myMonthlyIncome) else { return 0 }
        guard let housemateMonthlyIncome = Double(housemateMonthlyIncome) else { return 0 }
        let totalIncome = Double(myMonthlyIncome + housemateMonthlyIncome)
        let percentage = Double(myMonthlyIncome / totalIncome)
        let value = Double(totalRent * percentage)

        return Double(round(100*value)/100)
    }
    

然后该值显示为表单的一部分:

  Section {
               Text("Your share: £\(yourShare)")
          }

我是 Swift 新手,我正在努力确保 yourShare 只有 2 位小数,例如150.50 美元,但目前显示为 150.50000 美元。我尝试将其四舍五入到小数点后两位是Double(round(100*value)/100),我也尝试使用无效的rounded() 方法。我搜索的其他 StackOverflow 文章建议使用这两种方法,但我无法弄清楚我在这里做错了什么?

【问题讨论】:

  • 显示 $ 符号的代码在哪里?因为那是应该做的地方。使用NumberFormatter(用于货币)。

标签: swift number-formatting


【解决方案1】:

您可以借助字符串插值直接在 Text 内部进行:

struct ContentView: View {
    let decimalNumber = 12.939010

    var body: some View {
        Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
    }
}

【讨论】:

    【解决方案2】:

    转换成小数点后2位的字符串:

    let yourShareString = String(format: "%.2f", yourShare)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      相关资源
      最近更新 更多