8

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?

HannahCarney
  • 3,441
  • 2
  • 26
  • 32

5 Answers5

32

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
Seref Bulbul
  • 1,163
  • 12
  • 14
10

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. :-)

daniel.gindi
  • 3,457
  • 1
  • 30
  • 36
  • Thanks for you help. I tried this, but sadly it didn't work. Can't find any information on the repo either :( – HannahCarney Jul 17 '15 at 11:22
  • 1
    @HannahLouisaCarney It does work. What have you tried? Maybe you are setting the wrong valueFormatter `property`? The different components have that property separate – daniel.gindi Jul 18 '15 at 19:24
  • You are right, sorry! I added: self.lineChartholder.leftAxis.valueFormatter = NSNumberFormatter() self.lineChartholder.leftAxis.valueFormatter?.minimumFractionDigits = 0 – HannahCarney Jul 20 '15 at 09:09
  • This doesn't quite work. If the axis range is too small, e.g. 5-8, with 7 gridlines, then it shows 5, 5, 6, 6, 6, 7, 7 in the axis. – andrewtweber Jan 28 '16 at 05:22
0

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
Community
  • 1
  • 1
Morgan
  • 1,280
  • 1
  • 14
  • 15
0

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
0

Swift4.2 ; Xcode 10.0 :

let numberFormatter = NumberFormatter()
numberFormatter.generatesDecimalNumbers = false
barChart.leftAxis.valueFormatter = DefaultAxisValueFormatter.init(formatter: numberFormatter)
Antony Wong
  • 562
  • 5
  • 17