0

I'm using the below code and I'm trying to get my 'outputvalue' to round UP to two decimal places on button press.

I've found various different methods online and tried to incorporate them but with no luck. Could some point me in the right direction please?

If the calculation comes out to 164.98001 then I'd like the answer to display 164.99.

edit - I don't think this is a duplicate question as my question relates to rounding UP all numbers.

@IBAction func buttoncalc(_ sender: Any) {
    total.isHidden = false
    let firstValue = Double(text1.text!)
    let secondValue = Double(text2.text!)
    let thirdValue = Double(text3.text!)
    let forthValue = Double(text4.text!)


    if firstValue != nil && secondValue != nil && thirdValue != nil && forthValue != nil {

    let outputvalue = Double(((firstValue! * secondValue!)/1000)*0.5)*(thirdValue! - forthValue!)
    total.text = "£ \(outputvalue)"

    } else {
    total.text = nil
    }
}
suxrule
  • 55
  • 7

1 Answers1

3

You can use NumberFormatter to get formatted number as String. Just limit number of decimal places to 2 and set roundingMode to up

let formatter = NumberFormatter()
formatter.roundingMode = .up
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let number = 164.98001
print(formatter.string(from: NSNumber(value: number)) ?? "") // 164.99

To improve your logic even more, you can set formatter's numberStyle and locale

formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_UK")
// £164.99

Your specific usage:

let string = formatter.string(from: NSNumber(value: outputvalue)) ?? ""
total.text = string
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40