Swift-如果小数等于0,如何从浮点数中删除小数?
我正在显示一个带小数点的距离,如果它等于0(例如:1200.0Km),我想删除此小数点,如何迅速做到这一点?我正在显示此数字,如下所示:
let distanceFloat: Float = (currentUser.distance! as NSString).floatValuedistanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"
回答:
var distanceFloat1: Float = 5.0var distanceFloat2: Float = 5.540
var distanceFloat3: Float = 5.03
extension Float {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
print("Value \(distanceFloat1.clean)") // 5
print("Value \(distanceFloat2.clean)") // 5.54
print("Value \(distanceFloat3.clean)") // 5.03
let distanceFloat: Float = (currentUser.distance! as NSString).floatValuedistanceLabel.text = String(format: distanceFloat == floor(distanceFloat) ? “%.0f" : "%.1f", distanceFloat) + "Km"
或作为扩展:
extension Float { var clean: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
以上是 Swift-如果小数等于0,如何从浮点数中删除小数? 的全部内容, 来源链接: utcz.com/qa/413600.html