The DecimalFormat class offers the following four such methods which can be used to easily set the maximum and/or minimum digits for decimal numbers.
As shown in the below table, two of these methods can set max/min digits for integer part while the other two methods can do the same for the fraction part of the decimal numbers as is evident from the method names.
setMaximumFractionDigits​(int newValue) | Sets the maximum number of digits allowed in the fraction portion of a number |
setMaximumIntegerDigits​(int newValue) | Sets the maximum number of digits allowed in the integer portion of a number |
setMinimumFractionDigits​(int newValue) | Sets the minimum number of digits allowed in the fraction portion of a number |
setMinimumIntegerDigits​(int newValue) | Sets the minimum number of digits allowed in the integer portion of a number |
The following example demonstrates the usage of above methods:
The above code produces the following output:
Original Num: 170180.24551
JVM Locale Formatted Num: 170,180.246
Pattern Formatted Num: 17,0180.2455
With Min/Max Fraction Digits: 17,0180.2455
With Min/Max Integer & Fraction Digits: 180.2455