简体   繁体   中英

NumberFormatter negative value to positive

I would like to convert a negative value into a positive one using NumberFormatter . The value should represent a percent change and should look like this: 1.46% even if the value is negative -1.46 .

There is a numberFormatter.negativeFormat , but I am unsure what the format should look like. I tried numberFormatter.negativeFormat = "0.00" but the percent sign disappears and I do not want to add it explicitly at the end, because I am using numberStyle

numberFormatter.numberStyle = .percent

Any ideas what would be the best solution?

You can extend the Double type to create a specific property that returns a String with the absolute value:

extension Double {
    var positivePercent: String {
        return abs(self).formatted(.percent)
    }
}

Usage:

let a = -0.0146
print(a.positivePercent)   // 1.46%

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