Brian Brian - 6 months ago 23
Swift Question

UIStepper.value becomes scientific notation

This is my code:

@IBAction func stepperChanged(sender: AnyObject) {
let stepper = sender as! UIStepper
stepper.stepValue = 0.1
stepper.minimumValue = 0.0
stepper.maximumValue = 1.0
print("stepper value: \(stepper.value)")
}


When I kept pressing the minus button, the output was:

stepper value: 0.2
stepper value: 0.1
stepper value: 1.38777878078145e-16
stepper value: 0.0


Why there was
1.38777878078145e-16
between 0.1 and 0.0?

I want to know the reason and how to fix it.

Thanks!

Answer

Please try minimum value as 0 and maximum value as 10.

override func viewWillAppear(animated: Bool) {
        sampleUIStepper.minimumValue = 0
        sampleUIStepper.maximumValue = 10
        sampleUIStepper.stepValue = 1
    }

Convert the UIStepper's sender value to required format and use it.

@IBAction func sampleStepperValueChanged(sender: AnyObject) {
        let stepper = sender as! UIStepper

        let convertedValue = (stepper.value/10) as Double
        print(convertedValue)

    }
Comments