尝试在 Swift 中组合数字和变量
Trying to combine a number and variable in Swift
我是一个新手,正在努力通过将数字和变量组合在一起来创建 0.2。但我想我以某种方式完全倒退了。有人可以帮忙吗?
//将'20%'的字符串变成'2'。
let tipPercent = tip.prefix(1)
//将字符串转换为'2'的Int
let tipPercent1: Int = Int(tipPercent) ?? 0
//所以现在我想将 0. 与变量 tipPercent1 结合起来。这将创建“0.2”
let twentyTipamount = (billamount * 0.tipPercent1) + billamount
您似乎只想将百分比字符串解析为数字。你应该使用 NumberFormatter
.
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en-US_POSIX")
// or whatever other locale that your tip is written in
numberFormatter.numberStyle = .percent
// if the tip cannot be parsed, use 0 as the default
let tipRate = numberFormatter.number(from: tip)?.doubleValue ?? 0
// or you can do something else:
// guard let tipRate = numberFormatter.number(from: tip)?.doubleValue else { ... }
// calculate the amount after tips
let totalAmount = billamount * (1 + tipRate)
我是一个新手,正在努力通过将数字和变量组合在一起来创建 0.2。但我想我以某种方式完全倒退了。有人可以帮忙吗?
//将'20%'的字符串变成'2'。
let tipPercent = tip.prefix(1)
//将字符串转换为'2'的Int
let tipPercent1: Int = Int(tipPercent) ?? 0
//所以现在我想将 0. 与变量 tipPercent1 结合起来。这将创建“0.2”
let twentyTipamount = (billamount * 0.tipPercent1) + billamount
您似乎只想将百分比字符串解析为数字。你应该使用 NumberFormatter
.
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en-US_POSIX")
// or whatever other locale that your tip is written in
numberFormatter.numberStyle = .percent
// if the tip cannot be parsed, use 0 as the default
let tipRate = numberFormatter.number(from: tip)?.doubleValue ?? 0
// or you can do something else:
// guard let tipRate = numberFormatter.number(from: tip)?.doubleValue else { ... }
// calculate the amount after tips
let totalAmount = billamount * (1 + tipRate)