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

怎甘沉沦 提交于 2019-12-04 17:48:24

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/30663996/format-string-with-trailing-zeros-removed-for-x-decimal-places-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!