-2

What am I doing wrong?
I want to convert a Swift Double into a String.

let aaa: Double = 94.1
let bbb = String(format: "%d", aaa )
print("bbb:", bbb )

OUTPUT...

bbb: 1717986918

wzso
  • 3,482
  • 5
  • 27
  • 48
Doug Null
  • 7,989
  • 15
  • 69
  • 148
  • 2
    Because `%d` is for "integer" values, try `%f`. Interestingly, your code produces `"0"` for me. – MadProgrammer Jul 25 '23 at 23:28
  • 2
    You might consider using `NumberFormatter` instead, for [example](https://www.swiftbysundell.com/articles/formatting-numbers-in-swift/) and [example](https://developer.apple.com/documentation/foundation/numberformatter) – MadProgrammer Jul 25 '23 at 23:31
  • FYI - you may wish to see [What are the supported Swift String format specifiers?](https://stackoverflow.com/questions/52332747/what-are-the-supported-swift-string-format-specifiers) for more details about format specifiers. – HangarRash Jul 25 '23 at 23:43

4 Answers4

4

The format specifier %d is for integer values. For floating point you need to use %f. Note that this will default to 6 decimal places.

It would be much simpler to use string interpolation instead of old style printf style formatting.

let bbb = "\(aaa)"

You could also make use of NumberFormatter or the newer formatted on types like Double.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
1

For floating-point numbers like Double, you need to use the %f format specifier:

let aaa: Double = 94.1
let bbb = String(format: "%.1f", aaa)
print("bbb:", bbb)
Alexander
  • 59,041
  • 12
  • 98
  • 151
Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21
1

Or you can use NumberFormatter:

let double: Double = 94.1
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 2
if let string = formatter.string(for: double) {
    print(string) // 94.1
}

// or:
print(double.formatted()) // 94.1
wzso
  • 3,482
  • 5
  • 27
  • 48
  • 1
    No need for the `NSNumber`. Just change `formatter.string(from: number)` to `formatter.string(for: double)`. – HangarRash Jul 26 '23 at 01:27
0

To correctly convert a Double into a String representation with one decimal place, you should use the %0.1f format specifier. you can changed the format specifier according to your need.

Here is the corrected code:

let aaa: Double = 94.1
let bbb = String(format: "%.1f", aaa)
print("bbb:", bbb)

now it should display "94.1" as expected.

Madushan
  • 168
  • 5