简体   繁体   中英

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

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.

you can use this extension to do that job easily,

extension Double {
    func doubleTypeValueFormatter() -> String {
        let doubleValue = Double(self)
        let formatter = NumberFormatter()
        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: doubleValue as NSNumber) ?? "")
    }
}

And use that extension as like,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM