谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

totalWorkTime是一个NSTimeInterval (double),单位为秒。

totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......

当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?


当前回答

Swift 2扩展

一个更通用的解决方案是以下扩展,适用于Swift 2和iOS 9:

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}

Swift 3扩展

在Swift 3中,round被圆润取代:

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

返回Double四舍五入到小数点后4位的示例:

let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version

其他回答

我想知道是否有可能纠正用户的输入。也就是说,如果他们输入三个小数而不是两个小数来表示一美元的金额。比如说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


}

小数点后特定数字的代码为:

var a = 1.543240952039
var roundedString = String(format: "%.3f", a)

这里是%。3f告诉swift将这个数字四舍五入到小数点后3位。如果你想要双倍的数字,你可以使用这个代码:

//字符串为Double

var rounded弦= Double(字符串)(格式:%)。3f”,b型)

如果你想四舍五入Double值,你可能想要使用Swift Decimal,这样你就不会在尝试用这些四舍五入值计算时引入任何可能出现的错误。如果使用Decimal,则它可以准确地表示舍入浮点值的十进制值。

所以你可以这样做:

extension Double {
    /// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
    ///
    /// - Parameters:
    ///   - scale: How many decimal places to round to. Defaults to `0`.
    ///   - mode:  The preferred rounding mode. Defaults to `.plain`.
    /// - Returns: The rounded `Decimal` value.

    func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
        var decimalValue = Decimal(self)
        var result = Decimal()
        NSDecimalRound(&result, &decimalValue, scale, mode)
        return result
    }
}

然后,你可以像这样得到四舍五入的十进制值:

let foo = 427.3000000002
let value = foo.roundedDecimal(to: 2) // results in 427.30

如果你想用指定的小数位数来显示它(以及为用户的当前语言环境本地化字符串),你可以使用NumberFormatter:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
    print(string)
}

为了避免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

你可以使用Swift的round函数来实现这一点。

要对Double进行3位精度的四舍五入,首先将其乘以1000,四舍五入,然后将四舍五入结果除以1000:

let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236

与任何类型的printf(…)或String(format:…)解决方案不同,此操作的结果仍然是Double类型。

编辑: 关于它有时不能工作的评论,请阅读这篇:每个程序员都应该知道的关于浮点算术的事情