Reputation: 31282
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!
Upvotes: 0
Views: 249
Reputation: 272035
Double
s are not precise.
The type of UIStepper.value
is Double
. And Double
s' precision is only 16 - 17 digits. This means that in this code, result
is not equal to 0.1:
let a = 0.3
let b = 0.2
let result = a - b
// result might be 0.1000000000000000007890778643
So when you click the minus button, somewhere in the code there is this statement:
value -= stepValue
Since stepValue
is also a Double
, it is not precise. What is happening is that the step value might be equal to 0.9999999999999999138777878078145 when you click it the third time. Therefore, the stepper's value is not 0.
Another possible explanation would be that value
is not accurate, it might be 0.1000000000000000861222121021854
Remember, programming is not math.
How to solve this problem?
So you want to disable the minus button when it is close to 0, right? It's easy!
if stepper.value - 0 < 0.0000001 {
stepper.value = 0
}
Upvotes: 1
Reputation: 14296
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)
}
Upvotes: 4