本文介绍了迅捷-删除双精度的尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从双精度中删除尾随零的功能是什么?
What is the function that removes trailing zeros from doubles?
var double = 3.0
var double2 = 3.10
println(func(double)) // 3
println(func(double2)) // 3.1
推荐答案
在Swift 4中,您可以这样做:
In Swift 4 you can do it like that:
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
example of use: print (Double("128834.567891000").removeZerosFromEnd())
result: 128834.567891
您还可以计算字符串中有多少个十进制数字:
You can also count how many decimal digits has your string:
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) ?? "")
}
}
这篇关于迅捷-删除双精度的尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!