-1

I am using swift. I need to show float value in a UIlable. The scenario is like below:

if the value is like 1.50 it should show 1.5 only

and if the value is like 1.559 it should show 1.56

and if the value is like 2.0000 it should show only 2

and if the value is like 2.65 it should show only 2.65

Pravin S.
  • 465
  • 7
  • 22
  • 1
    Possible duplicate of [Precision String Format Specifier In Swift](http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift) – Aks Oct 06 '15 at 06:33
  • @Aks that wouldn't provide the behaviour the OP is asking for. – Steve Wilford Oct 06 '15 at 06:34
  • @SteveWilford then might be duplicate of this or it can be acheived by combination of existing answers: http://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift – Aks Oct 06 '15 at 06:38
  • I Just don't want to show digits if zero after Dot. – Pravin S. Oct 06 '15 at 07:21

1 Answers1

2

Use an NSNumberFormatter:

let nf = NSNumberFormatter()
nf.minimumFractionDigits = 1
nf.maximumFractionDigits = 2

print(nf.stringFromNumber(1.5)!)
print(nf.stringFromNumber(1.559)!)
Aderstedt
  • 6,301
  • 5
  • 28
  • 44