代码之家  ›  专栏  ›  技术社区  ›  0x1801CE

我可以使用SwiftUI.货币格式样式增加小数位数吗?

  •  1
  • 0x1801CE  · 技术社区  · 2 年前

    我想在我的文本和文本字段中使用.currency格式样式,但它将其限制在小数点后2位,并且我最多需要3或4位,例如燃料或股票价格。

    在本例中,价格四舍五入为2.10美元。我一直在使用.number还是自定义NumberFormatter?

    import SwiftUI
    
    struct SwiftUIView: View {
        @State private var price = 2.099
        var body: some View {
            TextField("Price", value: $price, format: .currency(code: "USD"))
            Text("\(price, format: .currency(code: "USD"))")
        }
    }
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   Sweeper    2 年前

    使用 fractionLength 指定所需的小数位数,作为一个范围。

    // show 2 or more decimal places
    Text("\(price, format: .currency(code: "USD").precision(.fractionLength(2...)))")
    

    此外,我建议使用 Decimal 以表示价格。

    @State private var price = Decimal(string: "2.099")!