swift - Swift 指定双精度而不转换为字符串
问题描述
我想将我的(滑块)指定为 2 位小数,但 xcode 不允许我这样做:
return (Double(pris, specifier: "%.2f"))
而且我不想将它转换为字符串然后格式化它,因为像 600000000 这样的数字是不可读的。
我尝试过以下解决方案:
extension Double {
// Rounds the double to 'places' significant digits
func roundTo(places:Int) -> Double {
guard self != 0.0 else {
return 0
}
let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
return (self * divisor).rounded() / divisor
}
}
解决方案
这应该做你需要的:
extension Double {
func roundedTo(places: Int) -> Double {
let conversion = pow(10.0, Double(places))
return (self * conversion).rounded() / conversion
}
}
print(10.125.roundedTo(places: 2)) // prints 10.13
print(10.124.roundedTo(places: 2)) // prints 10.12
推荐阅读
- beautifulsoup - BeautifulSoup 在同一个类标签中查找多个属性
- javascript - 在控制台期间取消定义结果
- python - 将 Julia 添加到 PATH 会导致其他人从 PATH 中退出 || Mac OSX
- r - 使用列表中的 data.table
- microsoft-graph-api - 属性“autoSubscribeNewMembers”和实际行为的问题
- c# - 具有多个值的枚举
- javascript - 如何找到一个文件巫婆时间戳路径
- window-server - 一个窗口服务器有多少个 CAL,其中包含 SQL Server?
- c# - 实体框架:一个或多个外键属性不可为空
- java - 使用杰克逊将命名列表反序列化为列表