0

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

Uma_Shanker_Tiwari
  • 453
  • 1
  • 3
  • 16
  • 2
    You 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 Answers2

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
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