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
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
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
.
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)
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
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.