This in Swift (1.2)
let doubleValue1 = Double(10.116983123)
println(String(format: "%.2f", doubleValue1))
let doubleValue2 = Double(10.0)
println(String(format: "%.2f", doubleValue2))
Prints
10.12
10.00
I'm looking for a way using a formatter or a direct string format and not via string manipulation, to remove the trailing zeroes, so to print:
10.12
10
The closest I got is:
let doubleValue3 = Double(10.0)
println(String(format: "%.4g", doubleValue3))
But g
uses significant digits, which means I would have to calculate my decimals digits separately. This sounds like an ugly solution.
Demo: http://swiftstub.com/651566091/
Any ideas? tia.
You have to use NumberFormatter:
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
print(formatter.string(from: 1.0000)!) // 1
print(formatter.string(from: 1.2345)!) // 1.23
This example will print 1 for the first case and 1.23 for the second; the number of minimum and maximum decimal places can be adjusted as you need.
I Hope that helps you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With