In my app I am dealing with currency which is need to upto two decimal digit , I have used number formatter for this to display up to two decimal place but When I want this double value up like 0.7 to 0.70 , I am unable to to do that , type double is always giving me 0.7 but i want 0.7 to 0.70
Asked
Active
Viewed 1.3k times
0
-
2You want a func that convert a double value to a string with the formatted value? What did you try? – FredericP Jun 04 '16 at 12:36
-
I want a double upto 2 decimal places – Uma_Shanker_Tiwari Jun 04 '16 at 12:45
-
@Uma_Shanker_Tiwari Strings contain formatting information, doubles don't – therefore you cannot add trailing zeros to their value. If you simply want to round a double to a set number of decimal places, then [see this Q&A](http://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift). – Hamish Jun 04 '16 at 13:01
2 Answers
23
You can simply do this:
let pi = 3.14159
let text = String(format: "%.2f", arguments: [pi])
print(text) // output = 3.14

Duly Kinsky
- 996
- 9
- 11
-
`let val = 1.2345` `let nVal = Double(round(100*val)/100)` `print(nVal)` – Lalit Yadav May 13 '20 at 17:34
10
You should use NSNumberFormatter
:
let numberFormatter = NSNumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
let pi = 3.14159
let str = numberFormatter.stringFromNumber(pi)!
print(str)

Mike Henderson
- 2,028
- 1
- 13
- 32