Reputation: 3470
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
Upvotes: 0
Views: 1918
Reputation: 12044
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
Upvotes: 2
Reputation: 73206
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 */
Upvotes: 1
Reputation: 285250
CGFloat
can't do that, convert the float back to String
print(String(format: "%.2f", flt)) // 19.30
Upvotes: 4