简体   繁体   中英

How to make a full decimal point for a calculator on swift?

I've just started to study Xcode. I've made all digits and math signs, but have no clue how to make a dot for calculator.

This is what I've done (deleted some repeating parts of math operations):

class ViewController: UIViewController {

    var numberFromScreen: Double = 0
    var firstNum: Double = 0
    var operation: Int = 0
    var mathSign: Bool = false


    @IBOutlet weak var result: UILabel!
    @IBAction func digits(_ sender: UIButton) {

        if mathSign == true {
            result.text = String (sender.tag)
            mathSign = false
        }
        else {
            result.text = result.text! + String (sender.tag)
        }

        numberFromScreen = Double (result.text!)!
    }
    @IBAction func buttons(_ sender: UIButton) {
        if result.text != "" && sender.tag != 10 && sender.tag != 15 {
        firstNum = Double (result.text!)!

            if sender.tag == 11 {// divine
                result.text = "/"

            }


            operation = sender.tag
            mathSign = true
        }
        else if sender.tag == 15 {// calculate
            if operation == 11 {
                result.text = String(firstNum / numberFromScreen)
            }
        }
        else if sender.tag == 10 {
            result.text = ""
            firstNum = 0
            numberFromScreen = 0
            operation = 0
        }
    }
}

In your case using the NumberFormatter would be a good option.

You can define it as follows:

private var formater: NumberFormatter {
    let formater = NumberFormatter()
    formater.maximumIntegerDigits = 9  // Change this value
    formater.maximumFractionDigits = 9 // Change this value 
    formater.minimumFractionDigits = 9 // Change this value 
    formater.minimumIntegerDigits = 1  // Change this value 
    formater.maximumIntegerDigits = 9  // Change this value 
    formater.groupingSeparator = " "
    formater.locale = Locale.current
    formater.numberStyle = .decimal
    return formater
}

And when you are setting the result to the label, you can go:

result.text = formater.string(from: NSDecimalNumber(value: yourValue))

If you are making a calculator I would recommend you that for bigger numbers or for numbers with many decimal places, you set the numberStyle property to .scientific .

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