Home > other >  How can I convert double value to money formate in SWIFT?
How can I convert double value to money formate in SWIFT?

Time:01-31

In my project, I need to convert price value (double/float) of some products to represent properly. If the value has any decimal value, it should show max two digit, otherwise it should not show any decimal value.

I have tried some large logical codes but I need a common method to do this job.

CodePudding user response:

you can use this extension to do that job easily,

extension Double {
    func removeZerosFromEnd() -> String {
        let doubleValue = Double(self)
        let formatter = NumberFormatter()
        let number = NSNumber(value: self)
        formatter.minimumFractionDigits = Double(Int(doubleValue)) < doubleValue ? 2 : 0 //minimum digits in Double after dot
        formatter.maximumFractionDigits = 2 //maximum digits in Double after dot
        return String(formatter.string(from: number) ?? "")
    }
}

And use that extension as like,

let withDecimal = (100.055).removeZerosFromEnd()
let withoutDecimal = (100.0).removeZerosFromEnd()

Here "withDecimal" will be 100.05 and "withoutDecimal" will be 100.

  • Related