Swift 数字类型文本 去除小数无效的0

2022-06-10  本文已影响0人  _风雨

OC

NSString * stringNumber = [NSString stringWithFormat:@"%.1f", 2.0];
NSNumber * inNumber = @(stringNumber.floatValue);
NSString * outNumber = [NSString stringWithFormat:@"%@",inNumber];
NSLog(@"%@", outNumber);

Swift

let stringNumber = String(format: "%.1f", 2.0)
let inNumber = NSNumber(value: Float(stringNumber) ?? 0.0)
let outNumber = "\(inNumber)"

另一种实现

extension BinaryFloatingPoint where Self: CustomStringConvertible {
    /// 数字类型文本
    ///
    /// 可自定义有效小数位
    /// example:
    ///    var num: Float = 8.0
    ///    num.ec_description()     //"8"
    ///
    ///    num = 8.100
    ///    num.ec_description()     //"8.1"
    ///
    ///    num = 8.888
    ///    num.ec_description()     //"8.888"
    ///    num.ec_description(significand: 2)   //"8.89"
    ///
    /// - parameter significand: 小数的有效位数

    func ec_description(significand:Int? = nil) -> String {
        
        let number = Int(self)
        if Self(number) == self { return number.description }
        guard let significand = significand else { return self.description }
        return String(format: "%.\(significand)f", self as! CVarArg)
    }
    
}

参考链接1
参考链接2

上一篇下一篇

猜你喜欢

热点阅读