谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
当前回答
这是一个更灵活的算法舍入到N位有效数字
Swift 3解决方案
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
}
}
// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200
其他回答
这里有一个SwiftUI,如果你需要一个文本元素的数字值。
struct RoundedDigitText : View {
let digits : Int
let number : Double
var body : some View {
Text(String(format: "%.\(digits)f", number))
}
}
这是一个更灵活的算法舍入到N位有效数字
Swift 3解决方案
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
}
}
// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200
使用内置的达尔文基金会图书馆
斯威夫特3
extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return Darwin.round(self * divisor) / divisor
}
}
用法:
let number:Double = 12.987654321
print(number.round(to: 3))
输出:12.988
小数点后特定数字的代码为:
var a = 1.543240952039
var roundedString = String(format: "%.3f", a)
这里是%。3f告诉swift将这个数字四舍五入到小数点后3位。如果你想要双倍的数字,你可以使用这个代码:
//字符串为Double
var rounded弦= Double(字符串)(格式:%)。3f”,b型)
你可以添加这个扩展:
extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
}
}
像这样叫它:
let ex: Double = 10.123546789
print(ex.clean) // 10.12