Home > Software engineering >  Using ValueFormatter in MP Chart but it does not taking effect
Using ValueFormatter in MP Chart but it does not taking effect

Time:12-30

Using MP Chart in Android. Reference : https://github.com/PhilJay/MPAndroidChart

I have to display 30.8351 as 30.83 on the BAR Chart.

So I found that We can do it with the use of Value Formater in MP Chart.

So I have created class for it as below :

class MyValueFormatter : ValueFormatter() {
override fun getFormattedValue(
    value: Float,
    entry: Entry,
    dataSetIndex: Int,
    viewPortHandler: ViewPortHandler
): String {
    var mFormat : DecimalFormat=DecimalFormat("###,###,##0.0")
    return mFormat.format(value)   " $"
 }
}

and then setting this to my chart's dataset as below :

val set1: BarDataSet
set1.setValueFormatter(MyValueFormatter())

But Still its displaying 30.8351 instead of 30.83 above the Bar Graph i.e. as a value of BAR.

What might be the Issue ?

EDIT BELOW AFTER JEEL ANSWERED

I have used Value Formator as below now:

set1.valueFormatter= object : ValueFormatter() {
                    override fun getFormattedValue(value: Float): String {
                        var mFormat : DecimalFormat = DecimalFormat("##.##")
                        return mFormat.format(value)
                    }
                }

But for the value -0.594 I am getting -0.6 It should be -0.59 only.

For 1.234 it's 1.23 (OKAY)

But for 1.235 it's 1.24 (NOT OKAY) - it should not round the value.

What might be the issue ?

CodePudding user response:

According to version 3.1.0 of MPAndroidChart,

The method of ValueFormatter that you're using is deprecated.

In order to use formatted value, one should either use specific method according to graph type or else use general method getFormattedValue(float value) (single argument method).


The method used in the O.P. is deprecated according to the document here which might be the reason that formatter isn’t working on the chart.

You should either use getBarLable(BarEntry barEntry) for the bar chart or else getFormattedValue(float value) in general to format the label.

Follow this document for more info.

CodePudding user response:

Note : Do not use deprecated method. (As per the above Jeel's Answer.)

It was the issue with Rounding of the Values. Done as below finally :

df.roundingMode = RoundingMode.CEILING

     set1.valueFormatter= object : ValueFormatter() {
     override fun getFormattedValue(value: Float): String {
                val df = DecimalFormat("##.##");
                df.roundingMode = RoundingMode.CEILING
                return df.format(value)
             }
           }
  • Related