NSNumberFormatter:大量显示 'k' 而不是 ',000'?

NSNumberFormatter : Show 'k' instead of ',000' in large numbers?

如果可能的话,我想将我的大数字从 100,000 改为 100,000 美元。

这是我目前拥有的:

let valueFormatter = NSNumberFormatter()
valueFormatter.locale = NSLocale.currentLocale()
valueFormatter.numberStyle = .CurrencyStyle
valueFormatter.maximumFractionDigits = 0

我的问题

使用 NSNumberFormatter,如何输出 $100K 而不是 $100,000?


我原来的问题:

这是我目前拥有的:

self.lineChartView.leftAxis.valueFormatter = NSNumberFormatter()
self.lineChartView.leftAxis.valueFormatter?.locale = NSLocale.currentLocale()
self.lineChartView.leftAxis.valueFormatter?.numberStyle = .CurrencyStyle
self.lineChartView.leftAxis.valueFormatter?.maximumFractionDigits = 0

转换为:

let valueFormatter = NSNumberFormatter()
valueFormatter.locale = NSLocale.currentLocale()
valueFormatter.numberStyle = .CurrencyStyle
valueFormatter.maximumFractionDigits = 0

我的输出是这样的:

我的问题

使用 NSNumberFormatter,如何输出 $100K 而不是 $100,000?


更新:

我想提供有关正在发生的事情的上下文,请观看评论。

func setDollarsData(months: [String], range: Double) {

    var dataSets: [LineChartDataSet] = [LineChartDataSet]()

    var yVals: [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        // I'm adding my values here in value:, value takes a Double
        yVals.append(ChartDataEntry(value: county[userFavs[0]]![i], xIndex: i))
    }

    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals, label: self.userFavs[0])
    set1.axisDependency = .Left
                set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5))
     set1.setCircleColor(UIColor.redColor())
     set1.lineWidth = 2.0
     set1.circleRadius = 6.0
     set1.fillAlpha = 65 / 255.0

     dataSets.append(set1)

    let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())

    // this is where I set the number formatter
    self.lineChartView.gridBackgroundColor = UIColor.darkGrayColor()
    self.lineChartView.leftAxis.startAtZeroEnabled = false
    self.lineChartView.leftAxis.valueFormatter = NSNumberFormatter()
    self.lineChartView.leftAxis.valueFormatter?.locale = NSLocale.currentLocale()
    self.lineChartView.leftAxis.valueFormatter?.numberStyle = .CurrencyStyle
    self.lineChartView.leftAxis.valueFormatter?.maximumFractionDigits = 0

    // set it to the chart // END OF THE LINE
    self.lineChartView.data = data // outputs to my chart

    }

如您所见,一旦我将数字转储到 yVals 中,我就无法访问它们,因此这些扩展只有在我入侵框架后才能工作。

我想你可以给 NSNumberFormatter 添加一个扩展。试试下面的方法,我没有测试过所以如果需要编辑请在评论中告诉我

extension NSNumberFormatter {
    func dividedByK(number: Int)->String{
        if (number % 1000) == 0 {
            let numberK = Int(number / 1000)
            return "\(numberK)K"
        }
        return "\(number)"
    }
}

edit/update

Swift 3 或更高版本

extension FloatingPoint {
    var kFormatted: String {
        return String(format: self >= 1000 ? "$%.0fK" : "$%.0f", (self >= 1000 ? self/1000 : self) as! CVarArg )
    }
}

您可以像这样使用它来格式化您的输出:

10.0.kFormatted     // ""
100.0.kFormatted    // "0"
1000.0.kFormatted   // "K"
10000.0.kFormatted  // "K"
162000.0.kFormatted  // "2K"
153000.0.kFormatted  // "3K"
144000.0.kFormatted  // "4K"
135000.0.kFormatted  // "5K"
126000.0.kFormatted  // "6K"

我遇到了同样的问题并通过实现自定义格式化程序解决了它。 Swift 刚开始编码,所以代码可能不是最地道的。

open class KNumberFormatter : NumberFormatter {
    override open func string(for obj: Any?) -> String? {
        if let num = obj as? NSNumber {
            let suffixes = ["", "k", "M", "B"]
            var idx = 0
            var d = num.doubleValue
            while idx < 4 && abs(d) >= 1000.0 {
                d /= 1000.0
                idx += 1
            }
            var currencyCode = ""
            if self.currencySymbol != nil {
                currencyCode = self.currencySymbol!
            }

            let numStr = String(format: "%.1f", d)

            return currencyCode + numStr + suffixes[idx]
        }
        return nil
    }
}