美文网首页
Swift 数字类型文本 去除小数无效的0

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

作者: _风雨 | 来源:发表于2022-06-10 16:30 被阅读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

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/bjsbmrtx.html