Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of decimal places and plus one in Swift?

Tags:

ios

swift

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?

like image 903
Nawin Poolsawad Avatar asked Nov 27 '25 12:11

Nawin Poolsawad


2 Answers

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
like image 181
Leo Dabus Avatar answered Nov 29 '25 00:11

Leo Dabus


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
like image 45
Hitesh Surani Avatar answered Nov 29 '25 02:11

Hitesh Surani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!