Swift格式化字符串(如果不是整数)具有2个十进制数字 [英] Swift Formatting String to have 2 decimal numbers if it is not a whole number

查看:63
本文介绍了Swift格式化字符串(如果不是整数)具有2个十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要格式化的字符串,当它不是整数时,最多显示两位小数,但如果是整数,则不应该小数位.

I have a string that I would like to be formatted such that when it is not a whole number, it will display up to two decimal places but if it is a whole number, there should be no decimal places.

是否有更简便的方法快速完成此操作,还是我必须满足于if-else?

Is there an easier way to do this in swift or do I have to settle for an if-else?

推荐答案

您可以扩展FloatingPoint来检查它是否为整数,并使用条件将NumberFormatterminimumFractionDigits属性设置为0,如果是这样,则将其设置为2:

You can extend FloatingPoint to check if it is a whole number and use a condition to set the minimumFractionDigits property of the NumberFormatter to 0 in case it is true otherwise set it to 2:

extension Formatter {
    static let custom: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 2
        return formatter
    }()
}
extension FloatingPoint {
    var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
    var custom: String {
        Formatter.custom.minimumFractionDigits = isWholeNumber ? 0 : 2
        return Formatter.custom.string(for: self) ?? ""
    }
}


游乐场测试:


Playground testing:

1.0.custom    // "1"
1.5.custom    // "1.50"
1.75.custom   // "1.75"

这篇关于Swift格式化字符串(如果不是整数)具有2个十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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