在项目中一些数字的显示难免会取整显示,四舍五入后保留一位小数,然而当最后一位是0的时候,要省略掉这个‘.0’,下面方法利用roundf函数对小数点最后一位做判断是否是0
func qiuZhengshu(_ string:String)->String {
var newN = ""
if string.floatValue() > 10000 {
let number = string.floatValue() / 10000
let lastStr = formatFloat(number)
newN = "\(lastStr)" + "万"
}else if string.floatValue() > 1000 {
let number = string.floatValue() / 1000
let lastStr = formatFloat(number)
newN = "\(lastStr)" + "千"
}else {
newN = string + ""
}
return newN
}
func formatFloat(_ f:Float)->NSString {
let str = NSString(format: "%.1f", f)
let number = str.floatValue
let i = roundf(number)
if i == number {
return NSString(format: "%.0f", number)
}else {
return NSString(format: "%.1f", number)
}
}