【发布时间】:2019-11-14 00:38:19
【问题描述】:
Text("Värde \(Double(calc2, specifier: "%.2f").rounded())")
//错误
我正在转换一个使用双精度类型的Slider 值,但我无法指定它的格式?
我收到一个错误,xcode 告诉我使用信号(?)。我也尝试将其放入Int。
这里的正确做法是什么?
【问题讨论】:
标签: swift xcode format swiftui specifier
Text("Värde \(Double(calc2, specifier: "%.2f").rounded())")
//错误
我正在转换一个使用双精度类型的Slider 值,但我无法指定它的格式?
我收到一个错误,xcode 告诉我使用信号(?)。我也尝试将其放入Int。
这里的正确做法是什么?
【问题讨论】:
标签: swift xcode format swiftui specifier
你可以使用
Text("Värde \(calc2, specifier: "%.2f")")
将其转换为 2 位小数。
为了获得更大的灵活性,您可以使用格式化程序并在字符串上利用appendInterpolation。使用下面的函数或类似的东西
func customFormat(_ number: Double) -> String {
let customFormatter = NumberFormatter()
customFormatter.roundingMode = .down
customFormatter.maximumFractionDigits = 2
return "\(number, formatter: customFormatter)"
}
【讨论】:
我假设你想要类似的东西
Text("Värde \(String(format: "%.2f", calc2))")
【讨论】:
specifier: 是在 SwiftUI 中添加的
问题是Double(calc2, specifier: "%.2f") 是可选的
处理它,例如,使用Double(calc2, specifier: "%.2f")?.rounded() ?? 0.0
【讨论】: