简体   繁体   English

如何在swift上为计算器制作一个完整的小数点?

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

I've just started to study Xcode.我刚刚开始学习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.在您的情况下,使用NumberFormatter将是一个不错的选择。

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 .如果您正在制作计算器,我建议您将数字numberStyle属性设置为.scientific

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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