2

My code below will output a value of £.88 when a small calculation is completed.

But I would like to output £0.88

Is this possible?

I've found a few solutions but none are working with my code.

Thanks for any help.

@IBAction func buttoncalc2(_ sender: Any) {
        total2.isHidden = false
        let fifthValue = Double(text5!.text!)
        let sixthValue = Double(text6!.text!)

        if fifthValue != nil && sixthValue != nil {

            let outputvalue2 = Double(((fifthValue! * sixthValue!)/1000)*0.5)
            let formatter = NumberFormatter()
            formatter.roundingMode = .up
            formatter.minimumFractionDigits = 2
            formatter.maximumFractionDigits = 2
            let string = formatter.string(from: NSNumber(value: outputvalue2)) ?? ""
            total2.text = "£ \(string)"

        }else{
            total2.text = nil
        }
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Welcome to Stack Overflow. Swift was built based on Objective-C, so searching for Objective-C answers as well as Swift answers can be very helpful. I think this answer should help: https://stackoverflow.com/a/11131497/350538 – Tin Can Apr 08 '19 at 20:38
  • 1
    @TinCan despite the fact that this answer can provide working solution, I think that thinking about result of formatter as about currency can be right approach. – Robert Dresler Apr 08 '19 at 20:46
  • possible duplicate of https://stackoverflow.com/a/29783546/2303865 – Leo Dabus Apr 08 '19 at 20:48
  • 1
    Note that you can avoid force-unwrapping if you would use optional binding inside if statement: `if let fifthValue = fifthValue, let sixthValue = sixthValue {` – Robert Dresler Apr 08 '19 at 20:48
  • 1
    I agree with @RobertDresler. Even if adding the minimumIntegerDigits like I had, somewhat opaquely, suggested would work, using a currency formatter is clearer about the intent of your code. – Tin Can Apr 08 '19 at 20:49
  • Way too many uses of `!` in your code. Consider learning how to properly and safely unwrap optionals when you get a chance. – rmaddy Apr 08 '19 at 22:04
  • Thanks for everyones input. I do know my code is a bit sloppy and needs tidying up so will look in to it a bit closer. Thanks again – SlyDawgMackay Apr 09 '19 at 08:40

2 Answers2

1

Add

formatter.minimumIntegerDigits = 1
Razi Tiwana
  • 1,425
  • 2
  • 13
  • 16
1

Different approach:

Make your formatter "currency formatter". It will automatically add currency symbol and this missing zero for you

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

let string = formatter.string(from: NSNumber(value: outputvalue2)) ?? ""
print(string) // £0.88
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40