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

11,258

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!

Share:
11,258

Related videos on Youtube

ericosg
Author by

ericosg

CTO @ Exelia Technologies, Software Developer and Lecturer MCT, MCSD, MCPD, CCNP

Updated on September 16, 2022

Comments

  • ericosg
    ericosg over 1 year

    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.

  • Musa almatri
    Musa almatri over 5 years
    Great, I just added formatter.minimumIntegerDigits = 1 so if I the number on the left is zero it won't remove it, (0.200 will be 0.2 instead of .2)