skip to Main Content

I have a UISlider that has min value of 0 and a max value of 1.

When it stops it can be any number such as

3.2990444444444442

In this situation I want to increase the last number to a 3 as in

3.2990444444444443

But since it’s a slider, I’ll never know the exact number until it stops, so the number might be

0.0019881635 at which I would want to increase to 0.0019881636 or 0.999 to 1.0

How can I do this?

If it’s not clear what I want to do, no matter what the last digit is in the slider decimal value, I need to increase it by 1

A lot of the answers that I came across are in another language, not Swift

2

Answers


  1. Consider this solution:

    extension Float {
    func decimalCount() -> Int {
        if self == Float(Int(self)) {
            return 0
        }
    
        let integerString = String(Int(self))
        let doubleString = String(self)
        let decimalCount = doubleString.count - integerString.count - 1
    
        return decimalCount
    }
    
    mutating func increaseLast(){
        let powerfactor = pow(10, Float(decimalCount()))
        self = (self * powerfactor + 1) / powerfactor
        
     }
    }
    

    I didn´t test this thoroughly but it should work. Got the function decimalcount from this so answer

    Usage example:

    let array: [Float] = [0.999, 0.0004, 0.004, 0.009]
    
    array.forEach{
      var a = $0
      a.increaseLast()
      print($0)
      print(a)
    }
    

    prints:

    0.999
    1.0
    0.0004
    0.0005
    0.004
    0.005
    0.009
    0.01
    
    Login or Signup to reply.
  2. nextUp returns the next Float value greater than the given value.

    Note that if the slider is set to 1, it will return a value greater than 1, so you may want to clamp that value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search