0

I was trying to save the coordinates

(75.8572998 = 7 digits after decimal point)

to NSUSERDEFAULT.

But when I fetch it back it shows the value only up to 3 digits after decimal

i.e. 75.857.

I tried to convert the coordinates to string or float before saving it to user defaults.

But no luck.

let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
let latitude : Float = Float(locationValue.latitude)
print("location = \(latitude)")

NSUSERDEFAULT.set(latitude, forKey: "lat")
print(NSUSERDEFAULT.double(forKey: "lat"))


location = (30.9009991)
30.9009990692139
Minkle Garg
  • 723
  • 3
  • 9
  • 35
  • So, can you share that code you tried so far? – Kamran Nov 25 '18 at 08:19
  • Float and Double are *binary floating point* representations with limited *precision.* None of them can store the decimal fractions 75.8572998 or 30.9009991 exactly. – A good start for reading about this might be https://floating-point-gui.de or https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. – Martin R Nov 25 '18 at 10:01

1 Answers1

4

Swift 4.2 playground tested code to save larger numbers,

let cor = 75.8572998232
UserDefaults.standard.set(cor, forKey: "cor")
let v = UserDefaults.standard.double(forKey: "cor")
print("Coordinate value is: \(v)")

Output

Coordinate value is: 75.8572998232

Kamran
  • 14,987
  • 4
  • 33
  • 51
  • I have edited the question according to your given response. But now it is showing more than 7 digits after decimal. – Minkle Garg Nov 25 '18 at 09:26
  • 2
    An answer is more helpful if it *explains* the problem and the solution. – Martin R Nov 25 '18 at 09:56
  • 1
    @MinkleGarg I couldn't reproduce anything like that. If you have rounding issue then this [question](https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift) could help you fix that. You can round the value to a fix number of decimal points while saving and retrieving from `userdefaults`. – Kamran Nov 25 '18 at 12:48