-1

I am trying to reduce the amount of characters in a double. How Would I reduce this:

59.5220000

to

59.5

this in swift?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    You should look into the [NumberFormatter class](https://developer.apple.com/documentation/foundation/numberformatter). It may look daunting because it uses another class `NSNumber`, but NSNumbers are easily initialized from Doubles – AgRizzo Jun 05 '19 at 18:34
  • Are you simply trying to round the result to once decimal place in the user interface? Or do you really need the number rounded for other reasons? – Rob Jun 05 '19 at 20:30

2 Answers2

2

A double doesn't have characters. A string rendering of it does. Rather than using the standard String() initializer (which is really only for development use, it's terrible for end-users), use NumberFormatter.

Alexander
  • 59,041
  • 12
  • 98
  • 151
0

perhaps use a formatted string?

let str = String(format: "%.2f", 59.5220000)
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • If this string is for display in the user interface, this `String(format:_:)` is not localized. `NumberFormatter` is much better solution for displaying results in the UI... – Rob Jun 05 '19 at 20:29