Reputation: 249
I need to implement plus function on last decimal place like
print(plusOne(0.0001)) -> 0.0002
print(plusOne(0.000001)) -> 0.000002
print(plusOne(22)) -> 23
Has anyone ever done about this?
Upvotes: 2
Views: 640
Reputation: 236260
You can get your value ulp property and add it:
let decimal1 = Decimal(string: "0.0001")!
let next1 = decimal1 + decimal1.ulp // 0.0002
let decimal2 = Decimal(string: "0.000001")!
let next2 = decimal2 + decimal2.ulp // 0.000002
let decimal3 = Decimal(string: "22")!
let next3 = decimal3 + decimal3.ulp // 23
or just simply get your nextUp or nextDown properties
decimal1.nextUp // 0.0002
decimal2.nextUp // 0.000002
decimal3.nextUp // 23
decimal1.nextDown // 0
decimal2.nextDown // 0
decimal3.nextDown // 21
Upvotes: 8
Reputation: 13537
truncatingRemainder(dividingBy:) Will help you to find the solution. Please refer to the below code snippet.
let x:Double = 1234.5678
let decimalPart:Double = x.truncatingRemainder(dividingBy: 1) //0.5678
let integerPart:Double = x.rounded(.towardZero) //1234
Upvotes: 1