Search code examples
javajfreechartdecimalformat

Removing last three zeros with DecimalFormat


I'm using jfreechart to display axis values in milliseconds but I'd like to show the axis labels in seconds, so I'd use domainAxis.setNumberFormatOverride(new DecimalFormat("???"));

So what's the syntax to remove last three zeros? e.g.: 1.000, 2.000, 3.000 to 1, 2, 3.


Solution

  • Thanks to this other post I managed to divide by 1000 subclassing NumberFormat

    So final code is simply:

    private static final NumberFormat THOUSANDS = new NumberFormat() {
    
        @Override
        public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
    
            new DecimalFormat().format(number / 1000D, toAppendTo, pos);
    
            return toAppendTo;
        }
    
        @Override
        public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
            return format((double) number, toAppendTo, pos);
        }
    
        @Override
        public Number parse(String source, ParsePosition parsePosition) {
            return null;
        }
    };
    

    And the call:

    domainAxis.setNumberFormatOverride(THOUSANDS);