iOS小數四捨五入總結

搶手的哥發表於2019-01-28

iOS專案裡,涉及到double型別是資料,經常會用到四捨五入這樣的取值方式,網上查閱資料之後,經常會不起作用,最終把有效的方法,總結了一下。 OC:

/**
 四捨五入字串

 @param round 小數位 eg: 2
 @param numberString 數字 eg 0.125
 @return 四捨五入之後的 eg: 0.13
 */
- (double )roundNumberStringWithRound:(NSInteger)round numberString:(NSString *)numberString{
    
    if (numberString == nil) {
        return 0;
    }
    NSDecimalNumberHandler *roundingBehavior    = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:round raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *aDN                        = [[NSDecimalNumber alloc] initWithString:numberString];
    NSDecimalNumber *resultDN                   = [aDN decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return resultDN.doubleValue;
}

複製程式碼

Swift:

    /// 四捨五入2位小數小數
    ///
    /// - round: 小數位(預設2位小數)
    /// - Parameter numberString: 格式化之前 eg 0.125
    /// - Returns: 格式化之後 eg: 0.13
    func roundNumberString(round:Int = 2, numberString : String) -> Double {
        if numberString.isEmpty || round == 0 {
            return 0.0
        }
        
        let roudingBehavior     = NSDecimalNumberHandler(roundingMode: .plain, scale: Int16(round), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        let aDn                 = NSDecimalNumber(string: numberString)
        let resultDn            = aDn.rounding(accordingToBehavior: roudingBehavior)
        return resultDn.doubleValue
        
    }

複製程式碼

相關文章