Paras Gorasiya
Paras Gorasiya

Reputation: 1351

iOS Charts framework maximumFractionDigits not working

I am using iOS Charts framework to show bar chart on my app. My leftAxisFormatter is like this

let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.minimumFractionDigits = 0
leftAxisFormatter.maximumFractionDigits = 2
leftAxisFormatter.positivePrefix = "$"

My data set is like this

0 : ChartDataEntry, x: 0.0, y 0.0
1 : ChartDataEntry, x: 1.0, y 7.6
2 : ChartDataEntry, x: 2.0, y 0.0
3 : ChartDataEntry, x: 3.0, y 0.0
4 : ChartDataEntry, x: 4.0, y 48.07
5 : ChartDataEntry, x: 5.0, y 107.26
6 : ChartDataEntry, x: 6.0, y 0.0

I am showing value using BalloonMarker When I tap a bar from chart but the value in marker always shows only one fraction digit, I have tried playing with NumberFormatter but no luck.

Please refer below screen shot in which I want to show 2 fraction digits for value shown into Marker, here it should be 107.26 according to my dataset.

enter image description here Please suggest me what am I doing wrong?

Thanks

Upvotes: 1

Views: 403

Answers (2)

Kamran
Kamran

Reputation: 15258

You can create your custom Markers. For simplicity, you can subClass BalloonMarker and override setLabel to format the value before passing to super's setLabel,

class MyCustomBaloon: BalloonMarker {

    override func setLabel(_ newLabel: String) {
        let value = String(format: "$%.2f", Double(newLabel) ?? 0.0)
        super.setLabel(value)
    }
}

Usage

let marker = MyCustomBaloon(color: UIColor(white: 180/255, alpha: 1),
                            font: .systemFont(ofSize: 12),
                            textColor: .white,
                            insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8))
marker.chartView = chartView
marker.minimumSize = CGSize(width: 80, height: 40)
chartView.marker = marker

Result

enter image description here

Upvotes: 2

Kamran
Kamran

Reputation: 15258

Your number formatter will return 2 digit fraction if there are more than 2 fraction digits otherwise it will return the same fraction digits that number has. For example, see the below outputs,

let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.minimumFractionDigits = 0
leftAxisFormatter.maximumFractionDigits = 2
leftAxisFormatter.positivePrefix = "$"

let number = 82.2343
print(leftAxisFormatter.string(for: number))

Optional("$82.23")

let number = 82
print(leftAxisFormatter.string(for: number))
Optional("$82")

let number = 82.1
print(leftAxisFormatter.string(for: number))
Optional("$82.1")

So, If you always want to get 2 digit fraction then just set the minimum to 2 as,

leftAxisFormatter.minimumFractionDigits = 2

Now all the outputs will be 2 digit as below,

Optional("$82.23")
Optional("$82.00")
Optional("$82.10")

Upvotes: 0

Related Questions