1

I am trying to format the y-axis of charts I am creating (JFreeCharts)

DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(5); 
numberTickUnit = new NumberTickUnit(numberTickUnit.getSize(), df);

Some charts have a range from say 0-15, so I want the numbers to have 2 decimals. Some charts have a range from 0.001 to 0.002, so I want the numbers to have 5 decimals.

The code above works well, with 1 issue. I want all the numbers on the axis to have the same format (the maximum number of decimals). So if I have 0.01251, 0.02000, 0.27490, I want it to display like that, as opposed to 0.01251, 0.02, 0.2749. How do I make the entire axis have the same format, instead of setting it separately for each number.

user101
  • 175
  • 1
  • 10

2 Answers2

2

I want the numbers to have 5 decimals.

Use setMinimumFractionDigits(), which "Sets the minimum number of digits allowed in the fraction portion of a number."

image

XYPlot plot =  (XYPlot) chart.getPlot();
NumberAxis range = (NumberAxis) plot.getRangeAxis();
NumberFormat formatter = DecimalFormat.getInstance();
formatter.setMinimumFractionDigits(5);
range.setNumberFormatOverride(formatter);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

I had to do it manually.

static NavigableMap<Double, String> decimalFormatMap = new TreeMap<Double, String>();
static
{
    decimalFormatMap.put(0.00001, "0.000001");
    decimalFormatMap.put(0.0001, "0.00001");
    decimalFormatMap.put(0.001, "0.0001");
    decimalFormatMap.put(0.01, "0.001");
    decimalFormatMap.put(0.1, "0.01");
    decimalFormatMap.put(1.0, "0.1");
    decimalFormatMap.put(100.0, "1");
}
NumberTickUnit numberTickUnit = * some key number *;
String decimalFormat = decimalFormatMap.get(
    decimalFormatMap.floorKey(numberTickUnit.getSize()));
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
user101
  • 175
  • 1
  • 10