0

I have the following in playground:

let a:CGFloat = 1.23
let b:Double = 3.45
let c:Float = 6.78
String(format: "(%2.2f|%2.2f|%2.2f)",a,b,c) // prints "(3.45|6.78|0.00)"
let d = NSMakePoint(9.87,6.54)
String(format: "(%2.2f|%2.2f)",d.x,d.y) // prints "(0.00|0.00)"

So why is c:Float rendered as 0.00. I possibly need something else than f (Apples docu on this formatting function is - to be polite - quite thin with a limes going to zero).

BUT: Why is the CGFloat in the first place rendered correctly while the two CGFloats inside the NSPoint get rendered as 0.00?

And no: it's not a duplicate of Precision String Format Specifier In Swift and its pendant.

P.S.

String(format: "(%2.2f|%2.2f)",Double(d.x),d.y) // prints  "(9.87|0.00)"

which is a work around but no explanation.

And a PPS: Isn't %2.2f supposed to print " 9.87" instead of "9.87" (2 places for leading digits? It seems to ignore the number. Specifying %02.2f also prints "9.87" rather than "09.87"

Community
  • 1
  • 1
qwerty_so
  • 35,448
  • 8
  • 62
  • 86

1 Answers1

1

CGFloat isn't a float or a double, it is its own struct. If you want the double or float value of a CGFloat (which is dependent on the architecture being 32 or 64 but, then you can access it with a.native. In other words try:

String(format: "(%2.2f|%2.2f|%2.2f)",a.native,b,c)

You'd see similar behavior if you tried to pass other non-float or non-double arguments to the %f formatter. For example:

var str = "Hello, playground"
String(format: "%2.2f|%2.2f|%2.2f", arguments: [str,b,c])

would result in "3.45|6.78|0.00". It appears to be looking for another float in your arguments to satisfy the last %f, and defaults to 0.00

As for the PPS. %2.2F is two decimal place and at least 2 total digits. If you wanted two digits minimum before the decimal, you'd want %5.2f. 5 because the decimal itself takes a place.

Jeremy Pope
  • 3,342
  • 1
  • 16
  • 17