在正%变化前加+号 [英] Add + sign in front of positive % change

查看:30
本文介绍了在正%变化前加+号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 API 获取数据以显示在我的 iOS 应用中.其中一些数据是一个百分比,所以当它是负数时,它会显示为 -0.98%,例如,没问题,但为了清楚起见,我希望正变化显示为 +0.98 而不是简单的 0.98.

I am fetching data from an API to be displayed in my iOS app. Some of this data is a percentage so when it is negative it is displayed as -0.98% for example, no problem, but for clarity I'd like positive variations to be displayed as +0.98 and not simply 0.98.

这是我更新标签时的代码:

Here is my code when I update the labels:

func updateBitcoinUI(with bitcoinInfo: Bitcoin) {
    DispatchQueue.main.async {
        self.bitcoinPercentageChangeLabel.text = String(format: "%.2f%%", Double(bitcoinInfo.percentChange24h) ?? 0)
    }
}

当百分比为正数时,有没有办法在字符串中添加 + 符号?

Is there a way to add the + symbol to the string when the percentage is positive?

推荐答案

这就是 NumberFormatter 的设计目的.使用此格式而不是硬编码格式将正确处理使用其他百分比和分隔符格式的语言环境中的本地化.例如:

This is what NumberFormatter is designed for. Using this rather than hard-coding the format will correctly handle localization in locales that use other percent and separator formats. For example:

var formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.positivePrefix = formatter.plusSign
formatter.maximumFractionDigits = 2

let value = 0.0098
formatter.string(for: value)    // +0.98%

formatter.locale = Locale(identifier: "ar")  // Arabic
formatter.string(for: value)    // ٠٫٩٨ ٪؜+

这篇关于在正%变化前加+号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆