简体   繁体   中英

convert a string to type double produces 0.0 instead of a supposed value

I am trying to convert a string to type double using Xcode. I've tried some methods I've seen on stack, but my results aren't properly coming out.

例子

In the image above, I am trying to add a tax of 10% to the button Total Cost. in this example it is $35. So the tax $3.50 and the total would be $38.50 The code I use allows me to get the double, but it is only set as 0.0 instead of what should be coming up. I am fetching this number that is stored in firebase and setting it as my money label.

  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)
}

Adding $ to priceString is the issue. Due to this the conversion fails and it returns 0.0. Here's the working code.

func configureButtonToSetPrice() {
    var moneyLabel: String = "35"
    let myFloat = (moneyLabel as NSString).doubleValue
    let withTax = "\(myFloat * 0.10 + myFloat)"
    print("Total Cost $\(withTax)")
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM