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)
}
}
网友评论