将字符串转换为 double 类型会产生 0.0 而不是假定的值
convert a string to type double produces 0.0 instead of a supposed value
我正在尝试使用 Xcode 将字符串转换为双精度类型。我已经尝试了一些我在堆栈上看到的方法,但我的结果没有正确出现。
在上图中,我试图向按钮总成本添加 10% 的税。在这个例子中是 35 美元。所以税金为 3.50 美元,总计为 38.50 美元。我使用的代码允许我获得双倍,但它只设置为 0.0,而不是应该出现的值。我正在获取存储在 firebase 中的这个数字并将其设置为我的货币标签。
var moneyLabel: UILabel = {
let label = UILabel()
label.text = "$"
label.font = UIFont.systemFont(ofSize: 20)
label.numberOfLines = 0
return label
}()
func setupViews() {
let post = notification?.poster
let cost = post?.cost
let priceString = cost != nil ? "$\(cost!)" : "N\A"
self.moneyLabel.text = priceString
self.moneyLabel.font = UIFont.systemFont(ofSize: 20)
self.moneyLabel.textColor = UIColor.black
configureButtonToSetPrice()
}
func configureButtonToSetPrice() {
let priceString = "$\(moneyLabel)"
let myFloat = (priceString as NSString).doubleValue
let withTax = "\(myFloat * 0.10 + myFloat)"
Pay.setTitle("Total Cost \(withTax)", for: .normal)
}
将 $ 添加到 priceString 是问题所在。因此转换失败并且它 returns 0.0.这是工作代码。
func configureButtonToSetPrice() {
var moneyLabel: String = "35"
let myFloat = (moneyLabel as NSString).doubleValue
let withTax = "\(myFloat * 0.10 + myFloat)"
print("Total Cost $\(withTax)")
}
希望对您有所帮助。
我正在尝试使用 Xcode 将字符串转换为双精度类型。我已经尝试了一些我在堆栈上看到的方法,但我的结果没有正确出现。
在上图中,我试图向按钮总成本添加 10% 的税。在这个例子中是 35 美元。所以税金为 3.50 美元,总计为 38.50 美元。我使用的代码允许我获得双倍,但它只设置为 0.0,而不是应该出现的值。我正在获取存储在 firebase 中的这个数字并将其设置为我的货币标签。
var moneyLabel: UILabel = {
let label = UILabel()
label.text = "$"
label.font = UIFont.systemFont(ofSize: 20)
label.numberOfLines = 0
return label
}()
func setupViews() {
let post = notification?.poster
let cost = post?.cost
let priceString = cost != nil ? "$\(cost!)" : "N\A"
self.moneyLabel.text = priceString
self.moneyLabel.font = UIFont.systemFont(ofSize: 20)
self.moneyLabel.textColor = UIColor.black
configureButtonToSetPrice()
}
func configureButtonToSetPrice() {
let priceString = "$\(moneyLabel)"
let myFloat = (priceString as NSString).doubleValue
let withTax = "\(myFloat * 0.10 + myFloat)"
Pay.setTitle("Total Cost \(withTax)", for: .normal)
}
将 $ 添加到 priceString 是问题所在。因此转换失败并且它 returns 0.0.这是工作代码。
func configureButtonToSetPrice() {
var moneyLabel: String = "35"
let myFloat = (moneyLabel as NSString).doubleValue
let withTax = "\(myFloat * 0.10 + myFloat)"
print("Total Cost $\(withTax)")
}
希望对您有所帮助。