Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string with trailing zeros removed for x decimal places in Swift [duplicate]

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.

like image 724
ericosg Avatar asked Jun 05 '15 10:06

ericosg


1 Answers

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!

like image 180
Icaro Avatar answered Oct 26 '22 14:10

Icaro