HannahCarney
HannahCarney

Reputation: 3631

iOS-Charts Float to Integer YAxis

I'm building a chart using iOS-charts IOS CHART

I'm trying to convert the floats into int, but iOS-charts only allows for Floats in the data entry:

      let result = ChartDataEntry(value: Float(month), xIndex: i)

Does anyone know the method for making sure only ints are used?

Upvotes: 9

Views: 8069

Answers (6)

Piyush Kumar
Piyush Kumar

Reputation: 51

NSNumberFormatter gives duplicate values because it just convert decimal to integer. You can use below solution, It will not give any duplicate values. Also you can set minimum and maximum as per the requirement of the chart. Below worked for me as per my requirement.

        barChart.leftAxis.axisMinimum = max(0.0, 0.0)
        barChart.leftAxis.axisMaximum = min(10.0, barChart.data!.yMax + barChart.data!.yMin)
        barChart.leftAxis.labelCount = Int(barChart.leftAxis.axisMaximum - barChart.leftAxis.axisMinimum)
        barChart.leftAxis.drawZeroLineEnabled = false

Upvotes: 0

Antony  Wong
Antony Wong

Reputation: 592

Swift4.2 ; Xcode 10.0 :

let numberFormatter = NumberFormatter()
numberFormatter.generatesDecimalNumbers = false
barChart.leftAxis.valueFormatter = DefaultAxisValueFormatter.init(formatter: numberFormatter)

Upvotes: 0

LastNeoNotTheHero
LastNeoNotTheHero

Reputation: 1

You can try this one, it worked nicely for me

let formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
formatter.locale = NSLocale(localeIdentifier: "es_CL")
BarChartView.leftAxis.valueFormatter = formatter

Upvotes: 0

Seref Bulbul
Seref Bulbul

Reputation: 1173

For Swift 3.0 and Charts 3.0 you need to enable and set granularity for the axis.

Example:

barChart.leftAxis.granularityEnabled = true
barChart.leftAxis.granularity = 1.0

Upvotes: 33

Morgan
Morgan

Reputation: 1310

This worked for me. However, the y-axis labels will round when displaying small numbers, so if you are charting, say 1 or 2, the chart will display 0 twice. (See here: Force BarChart Y axis labels to be integers?)

let numberFormatter = NSNumberFormatter()
numberFormatter.generatesDecimalNumbers = false
chartDataSet.valueFormatter = numberFormatter
// Converting to Int for small numbers rounds weird
//barChartView.rightAxis.valueFormatter = numberFormatter
//barChartView.leftAxis.valueFormatter = numberFormatter

Upvotes: 0

daniel.gindi
daniel.gindi

Reputation: 3496

You just need to adjust the NSNumberFormatter...

Example:

yAxis.valueFormatter = NSNumberFormatter()
yAxis.valueFormatter.minimumFractionDigits = 0

NSNumberFormatter is a very powerful class, you can do much much more with it. :-)

Upvotes: 11

Related Questions