swift小数限制NumberFormatter

前端之家收集整理的这篇文章主要介绍了swift小数限制NumberFormatter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//多个属性可能会冲突
let numberFormate = NumberFormatter()

//最大有效数字位数
numberFormate.maximumSignificantDigits = 3
//最小效数字位数
numberFormate.minimumSignificantDigits = 3

//最小小数位数
//numberFormate.minimumFractionDigits = 1
//最大小数点位数
//numberFormate.maximumFractionDigits = 2
//最大整数位数
//numberFormate.maximumIntegerDigits = 2  //12.002 -> "2"
//最小整数位数 不够补“0”
//numberFormate.minimumIntegerDigits = 2

//numberFormate.maximum = NSNumber(value: 1)
//numberFormate.minimum = NSNumber(value: 1)

//有四舍五入属性:
     let numformate = NumberFormatter()
     numformate.string(from: 11.6)

others:
    numberFormate.allowsFloats
    numberFormate.usesSignificantDigits
    numberFormate.string(from: 1.100000010001)


示例:
/* 小数限制:2位小数,且要求当小于1时,必须留一位小数 */
func fomate(_ numberStr: String) -> String {
    let number = NSNumber(value: Double(numberStr) ?? 0)
    if number.doubleValue == 0 {
        return "0"
    }
    let formate = NumberFormatter()
    //最小整数位
    formate.minimumIntegerDigits = 1
    //最大小数
    formate.maximumFractionDigits = 2
    if fabs(number.doubleValue) < 0.01 {
        //最小小数位
        formate.minimumFractionDigits = 1
        //最大有效数字位
        formate.maximumSignificantDigits = 1
    }
    //formate.paddingCharacter = ""
    return formate.string(from: number) ?? "0"
}
//效果:
     fomate("-1.000109123456")//-1
     fomate("1.009109123456")//1.01
     fomate("0.000009823456")//0.00001

猜你在找的Swift相关文章