Incorrect rounding off result

Hi, what do you think is wrong with the fucntion. This is what I have. Could it be because of the roundmode type used?

static func roundOff(_ val: String, _ decimalPlace: Int) -> String {
    let decimalFormatter = createDecimalFormatter()
    decimalFormatter.minimumFractionDigits = decimalPlace
    decimalFormatter.maximumFractionDigits = decimalPlace

    let bigDecimal = NSDecimalNumber(string: val)
    return decimalFormatter.string(from: bigDecimal.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .up, scale: Int16(decimalPlace), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)))!
  }

  static func roundOff(_ value: Double, _ decimalPlace: Int) -> String {
    return roundOff(String(value), decimalPlace)
  }

roundOf("75.2", 0) returns 76 instead of 75

Accepted Reply

I will close this thread. I finally came across a post. the rounding mode used is .plain. Though I do not understand but since it works i have no problem with it.

Replies

I will close this thread. I finally came across a post. the rounding mode used is .plain. Though I do not understand but since it works i have no problem with it.

Your code says:

roundingMode: .up

So it rounds up from 75.2 to 76. Where is the confusion?

  • i didnt know what the use for the roundingmode was. i just chose whatever option in the list that popped up in xcode

Add a Comment