How to change DecimalFormat behavior based on input length?

I am using the following DecimalFormat template:

 // 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 

Now I have an additional requirement.

 1.123 -> 1.123 1.1234 -> 1.123 

This means that when

  • less than two decimal places, I will "work out" up to two decimal places.
  • there are exactly two or three decimal places, I won’t do anything.
  • there are more than three decimal places, I truncate to three decimal places.

Can this behavior be specified with the DecimalFormat class?

+8
java decimal format number-formatting decimalformat
source share
2 answers
 DecimalFormat("#,##0.00#") 
+4
source share

Have you tried changing the RoundingMode of your DecimalFormat instance?

A call to setRoundingMode(RoundingMode.FLOOR) should do the trick

See also setRoundingMode (java.math.RoundingMode)

+1
source share

Source: https://habr.com/ru/post/650086/


All Articles