0

I've found the documentation for remainder(dividingBy:), yet it's not clear to me how I could use this to say, round lonlat:[Double] like so:

[-73.983689245631894, 40.72751308705945]

to the 6th decimal:

[-73.983689, 40.727513]
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
  • https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift – Martin R Jan 10 '18 at 19:08
  • 1
    With fixed precision floating point (`Float`, `Double`), you can't. Consider using `Decimal`, or just using a `NumberFormatter` right before displaying it to a user. https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Alexander Jan 10 '18 at 19:08
  • Wow major dup, my bad, sorry. – JP Silvashy Jan 10 '18 at 19:08
  • Long read, but definitely worth it: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Alexander Jan 10 '18 at 19:08
  • @JPSilvashy Also, don't use array's to hold a fix pair of 2 elements! We have tuples in Swift! And `CLLocationCoordinate2D`! – Alexander Jan 10 '18 at 19:10
  • @Alexander much appreciated, just getting started this past week, stumbling like a moron! :) – JP Silvashy Jan 10 '18 at 19:10
  • you can use NumberFormatter and set minimum and maximum fraction digits as well as the routing mode https://stackoverflow.com/a/27705739/2303865 – Leo Dabus Jan 10 '18 at 19:12

2 Answers2

3

Use NumberFormatter

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.maximumFractionDigits = 6 // 6th decimal

let roundedValue1 = formatter.string(from: -73.983689245631894)

Reader then can generalize code.

0

You can cut your number with

let formatted = String(format: "number: %.6f", number)
sundance
  • 2,930
  • 1
  • 20
  • 25