简体   繁体   中英

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? eg: 1.000, 2.000, 3.000 to 1, 2, 3.

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);

Try this

String label= "1.000"
String slabel= new DecimalFormat("0.####").format(Double.parseDouble(label));
System.out.println(slabel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM