Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change DecimalFormat behavior based on input length?

I am using the following DecimalFormat pattern:

// Use ThreadLocal to ensure thread safety.
private static final ThreadLocal <NumberFormat> numberFormat =
  new ThreadLocal <NumberFormat>() {
    @Override protected NumberFormat initialValue() {
        return new DecimalFormat("#,##0.00");
    }
};

This performs the following conversions:

1    -> 1.00
1.1  -> 1.10
1.12 -> 1.12

I now have an additional requirement.

1.123  -> 1.123
1.1234 -> 1.123

That means that when

  • there are fewer than two decimal places, I will "pad" to two decimal places.
  • there are exactly two or three decimal places, I will do nothing.
  • there are more than three decimal places, I will truncate to three decimal places.

Can I specify this behavior with the DecimalFormat class?

like image 660
Cheok Yan Cheng Avatar asked Dec 13 '10 13:12

Cheok Yan Cheng


2 Answers

DecimalFormat("#,##0.00#")
like image 51
jzd Avatar answered Sep 22 '22 08:09

jzd


Have you tried to change the RoundingMode of your DecimalFormat instance?

Calling setRoundingMode(RoundingMode.FLOOR) should do the trick

See also setRoundingMode(java.math.RoundingMode)

like image 39
Robert Avatar answered Sep 22 '22 08:09

Robert