谁能告诉我如何在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 ?
当前回答
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
要将totalWorkTimeInHours四舍五入为3位数字以便打印,使用String构造函数,它接受一个格式字符串:
print(String(format: "%.3f", totalWorkTimeInHours))
其他回答
如果你想在逗号后面只有0表示圆,试试这个:
extension Double {
func isInteger() -> Any {
let check = floor(self) == self
if check {
return Int(self)
} else {
return self
}
}
}
let toInt: Double = 10.0
let stillDouble: Double = 9.12
print(toInt.isInteger) // 10
print(stillDouble.isInteger) // 9.12
在Swift 5.5和Xcode 13.2中:
let pi: Double = 3.14159265358979
String(format:"%.2f", pi)
例子:
附注:自Swift 2.0和Xcode 7.2以来一直如此
为了避免Float不完美,请使用Decimal
extension Float {
func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
var result: Decimal = 0
var decimalSelf = NSNumber(value: self).decimalValue
NSDecimalRound(&result, &decimalSelf, scale, rule)
return (result as NSNumber).floatValue
}
}
前女友。 1075.58在使用Float时四舍五入为1075.57 1075.58在使用十进制时四舍五入为1075.58,比例为2和。down
斯威夫特5
使用字符串方法
var yourDouble = 3.12345
//to round this to 2 decimal spaces i could turn it into string
let roundingString = String(format: "%.2f", myDouble)
let roundedDouble = Double(roundingString) //and than back to double
// result is 3.12
但是使用扩展更容易被接受
extension Double {
func round(to decimalPlaces: Int) -> Double {
let precisionNumber = pow(10,Double(decimalPlaces))
var n = self // self is a current value of the Double that you will round
n = n * precisionNumber
n.round()
n = n / precisionNumber
return n
}
}
然后你可以使用:
yourDouble.round(to:2)
这是一个更灵活的算法舍入到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