Silverstar Silverstar - 1 year ago 60
Swift Question

CGPoint readout inaccurate at extreme coordinates of 500,000,000

Why can I not get an accurate readout when at extreme coordinates for CGPoint?

For example if the CGPoint created for (500000250,500000100) and I use print() I only see "5e+08" for both x and y. When I use number formatter (see below) and convert the scientific notation back to a decimal I only get 500000000 for each x and y which is 250 and 100 out of sync.

let coordinates = CGPointMake(500000250,500000100)

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let xCoord = numberFormatter.numberFromString("\(coordinates.x)")
let yCoord = numberFormatter.numberFromString("\(coordinates.y)")

I've also tried:

let decimalValue = NSDecimalNumber(string: "\(coordinates.x)")

All the results will read out as 500000000 and the value cannot be stored for future use because it is inaccurate.

I must be missing something.

Answer Source

CGPoint uses CGFloat for the x and y coordinates.

On a 32-bit platform CGFloat is the type Float, which has about 6 significant digits. In your case the last three digits are rounded off.

If you move to a 64-bit platform CGFloat is the type Double which has at least 15 significant digits.

If you need to do calculations with 15 significant digits, do it with Double then cast to CGFloat when you pass it in to Core Graphics.