0

I am trying to convert a string into CGFloat number. The code I have cuts out the last digit if equal to 0.

How can I prevent to cut out the zeros?

let str = "17.30"

let flt = CGFloat((str as NSString).doubleValue) + 2.0

print(flt) // 19.3 -- should be 19.30
SNos
  • 3,430
  • 5
  • 42
  • 92
  • Are you trying to preserve the precision (number of decimals) originally used in the string, or do you always want to format the result with 2 decimals? – Stefan Mar 07 '16 at 13:45
  • I ma trying to format always the result with 2 decimals – SNos Mar 07 '16 at 13:46
  • @SNos If you want to convert a number to a string, use `NSNumberFormatter`. – Sulthan Mar 07 '16 at 13:48

3 Answers3

4

CGFloat can't do that, convert the float back to String

print(String(format: "%.2f", flt)) // 19.30
vadian
  • 274,689
  • 30
  • 353
  • 361
2

For swift 4

Try using NumberFormatter in .decimal format:

let text = "123456.789"

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let value = formatter.string(from: text! as NSNumber)!

print(value)

Output: 123,456.78
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
1

The CGFloat is just a number (so 17.3 and 17.30 is the same value for it); what you're really concerned is how to set the String representation of your CGFloat number.

As an alternative to @vadian:s solution, you can make use of an NSNumberFormatter as follows

/* Your CGFloat example */
let str = "17.30"
let flt = CGFloat((str as NSString).doubleValue) + 2.0

/* Use NSNumberFormatter to display your CGFloat 
   with exactly 2 fraction digits.  */
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
print(formatter.stringFromNumber(flt)!)
    /* 19.30 */
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • 1
    `?? ""` makes little sense in this case, you want to raise an exception when conversion fails (because it should never happen), not silently swallow it. I would use `!`. – Sulthan Mar 07 '16 at 14:16
  • 2
    @Sulthan You're right; stems from my (here: possibly bad) habit out of avoiding using `!` when answering SO questions out of fear of misguidedly teaching someone to use `!` for unwrapping in less appropriate situations. With these two comments, this will hopefully not be the case here, thanks for pointing this out! – dfrib Mar 07 '16 at 14:22