JP Silvashy
JP Silvashy

Reputation: 48535

Swift rounding to nearest nth decimal

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]

Upvotes: 0

Views: 253

Answers (2)

user3773246
user3773246

Reputation:

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.

Upvotes: 4

sundance
sundance

Reputation: 3030

You can cut your number with

let formatted = String(format: "number: %.6f", number)

Upvotes: 0

Related Questions