从双精度中删除尾随零的功能是什么?
var double = 3.0 var double2 = 3.10 println(func(double)) // 3 println(func(double2)) // 3.1
在Swift 4中,您可以这样做:
extension Double { func removeZerosFromEnd() -> String { let formatter = NumberFormatter() let number = NSNumber(value: self) formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 16 //maximum digits in Double after dot (maximum precision) return String(formatter.string(from: number) ?? "") } }
使用示例:print (Double("128834.567891000").removeZerosFromEnd()) 结果:128834.567891
print (Double("128834.567891000").removeZerosFromEnd())
您还可以计算字符串中有多少个十进制数字:
import Foundation extension Double { func removeZerosFromEnd() -> String { let formatter = NumberFormatter() let number = NSNumber(value: self) formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = (self.components(separatedBy: ".").last)!.count return String(formatter.string(from: number) ?? "") } }