在 Swift 中为 x 个小数位删除尾随零的格式字符串 [英] Format string with trailing zeros removed for x decimal places in Swift

查看:19
本文介绍了在 Swift 中为 x 个小数位删除尾随零的格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift (1.2) 中的这个

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

印刷品

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

我得到的最接近的是:

let doubleValue3 = Double(10.0)
println(String(format: "%.4g", doubleValue3))

但是 g 使用有效数字,这意味着我必须单独计算我的小数位数.这听起来像一个丑陋的解决方案.

But g uses significant digits, which means I would have to calculate my decimals digits separately. This sounds like an ugly solution.

演示:http://swiftstub.com/651566091/

有什么想法吗?tia.

Any ideas? tia.

推荐答案

你必须使用 NumberFormatter:

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

此示例将打印第一种情况的 1 和第二种情况的 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.

希望能帮到你!

这篇关于在 Swift 中为 x 个小数位删除尾随零的格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆