swift – NSNumberFormatter:大量显示’k’而不是’,000’?

前端之家收集整理的这篇文章主要介绍了swift – NSNumberFormatter:大量显示’k’而不是’,000’?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果可能的话,我想将我的大数字从100,000改为$100K.

这是我到目前为止:

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,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中,我就失去了对它们的访问权限,因此这些扩展只有在我入侵框架时才能工作.

编辑/更新

Swift 3或更高版本

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

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

10.0.kFormatted     // "$10"
100.0.kFormatted    // "$100"
1000.0.kFormatted   // "$1K"
10000.0.kFormatted  // "$10K"
162000.0.kFormatted  // "$162K"
153000.0.kFormatted  // "$153K"
144000.0.kFormatted  // "$144K"
135000.0.kFormatted  // "$135K"
126000.0.kFormatted  // "$126K"

猜你在找的Swift相关文章