Round Issue in swift

后端 未结 3 422
無奈伤痛
無奈伤痛 2021-01-07 14:58

I have this Info.

let params2: [String: AnyObject] = [
    \"app_token\": myapptoken,
    \"member_access_token\": accessToken!,
    \"pay_process\": 0,
             


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 15:17

    Try using this function:

    let price: Double = 9.87
    
    func roundDouble(num: Double) -> Float {
    
      //Create NSDecimalNumberHandler to specify rounding behavior
      let numHandler = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundDown, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
    
      let roundedNum = NSDecimalNumber(double: num).decimalNumberByRoundingAccordingToBehavior(numHandler)
    
      //Convert to float so you don't get the endless repeating decimal.
      return Float(roundedNum)
    
    }
    
    roundDouble(price) //9.87
    

    I think the best thing to do here is to explicitly use a float instead of a double because the precision of a double is not necessary if you only want two decimal places. This function just helps round it a bit more accurately.

提交回复
热议问题