Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Charts ValueFormatter

I am using iOS charts plugin (line chart) and wish to style the chart values (the number above each point) to a decimal number.

The value is a double, but charts by default is rounding it and displaying it as an integer.

I have tried the following but not working:

    let valueformatter = NumberFormatter()
    valueformatter.numberStyle = .decimal
    valueformatter.locale = Locale.current
    lineChartDataSet.valueFormatter = valueformatter as? IValueFormatter

I have tried various other properties but non of them change the format of the number in the dataset.

How can I change the format of the displayed number?

like image 266
George Filippakos Avatar asked Jun 28 '17 23:06

George Filippakos


4 Answers

Almost there, just need to add the following class:

class ChartValueFormatter: NSObject, IValueFormatter {
    fileprivate var numberFormatter: NumberFormatter?

    convenience init(numberFormatter: NumberFormatter) {
        self.init()
        self.numberFormatter = numberFormatter
    }

    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        guard let numberFormatter = numberFormatter
            else {
                return ""
        }
        return numberFormatter.string(for: value)!
    }
}

Now use this as the number formatter:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale.current
let valuesNumberFormatter = ChartValueFormatter(numberFormatter: numberFormatter)
lineChartDataSet.valueFormatter = valuesNumberFormatter
lineChartDataSet.valueFont = lineChartDataSet.valueFont.withSize(chartFontPointSize)
like image 164
George Filippakos Avatar answered Nov 04 '22 17:11

George Filippakos


   lineChartDataSet.valueFormatter = DefaultValueFormatter(decimals: 2)
like image 45
Jiebe Avatar answered Nov 04 '22 17:11

Jiebe


This worked for me:

Swift 5

let valFormatter = NumberFormatter()
valFormatter.numberStyle = .currency
valFormatter.maximumFractionDigits = 2
valFormatter.currencySymbol = "$"

lineChartPrice.leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: valFormatter)
like image 25
Arash HF Avatar answered Nov 04 '22 18:11

Arash HF


 let data = PieChartData(dataSet: set) 

 let formatter = NumberFormatter() 
 formatter.numberStyle = .percent 
 formatter.maximumFractionDigits = 2 
 formatter.multiplier = 1.0 
 formatter.percentSymbol = "%" 
 formatter.zeroSymbol = "" 
 data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
like image 36
rjgodoy Avatar answered Nov 04 '22 19:11

rjgodoy