谁能告诉我如何在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 ?
当前回答
这在Swift 5中似乎有效。
令人惊讶的是,现在还没有这样的标准函数。
//用四舍五入截断双位数到小数点后n位
extension Double {
func truncate(to places: Int) -> Double {
return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
}
}
其他回答
在Swift 5.5和Xcode 13.2中:
let pi: Double = 3.14159265358979
String(format:"%.2f", pi)
例子:
附注:自Swift 2.0和Xcode 7.2以来一直如此
:
Using String(format:): Typecast Double to String with %.3f format specifier and then back to Double Double(String(format: "%.3f", 10.123546789))! Or extend Double to handle N-Decimal places: extension Double { func rounded(toDecimalPlaces n: Int) -> Double { return Double(String(format: "%.\(n)f", self))! } } By calculation multiply with 10^3, round it and then divide by 10^3... (1000 * 10.123546789).rounded()/1000 Or extend Double to handle N-Decimal places: extension Double { func rounded(toDecimalPlaces n: Int) -> Double { let multiplier = pow(10, Double(n)) return (multiplier * self).rounded()/multiplier } }
我想知道是否有可能纠正用户的输入。也就是说,如果他们输入三个小数而不是两个小数来表示一美元的金额。比如说1.111而不是1.11,你能通过四舍五入来修复它吗?出于很多原因,答案是否定的!对于金钱,任何超过0.001的东西最终都会在真正的支票簿上产生问题。
下面是一个函数,用于检查用户输入的句点之后是否有太多值。但是它允许1。、1.1和1.11。
假设已经检查了该值,以成功地从String转换为Double。
//func need to be where transactionAmount.text is in scope
func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{
var theTransactionCharacterMinusThree: Character = "A"
var theTransactionCharacterMinusTwo: Character = "A"
var theTransactionCharacterMinusOne: Character = "A"
var result = false
var periodCharacter:Character = "."
var myCopyString = transactionAmount.text!
if myCopyString.containsString(".") {
if( myCopyString.characters.count >= 3){
theTransactionCharacterMinusThree = myCopyString[myCopyString.endIndex.advancedBy(-3)]
}
if( myCopyString.characters.count >= 2){
theTransactionCharacterMinusTwo = myCopyString[myCopyString.endIndex.advancedBy(-2)]
}
if( myCopyString.characters.count > 1){
theTransactionCharacterMinusOne = myCopyString[myCopyString.endIndex.advancedBy(-1)]
}
if theTransactionCharacterMinusThree == periodCharacter {
result = true
}
if theTransactionCharacterMinusTwo == periodCharacter {
result = true
}
if theTransactionCharacterMinusOne == periodCharacter {
result = true
}
}else {
//if there is no period and it is a valid double it is good
result = true
}
return result
}
不是斯威夫特,但我相信你明白我的意思。
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
一个方便的方法是使用Double类型的扩展
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
用法:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14