Search code examples
swiftnumber-formatting

How can I add a zero to the beginning of an answer that is less than 1.00 in swift xcode?


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
        }
    }

Solution

  • Add

    formatter.minimumIntegerDigits = 1