I would like to format a BigDecimal value according to the following rules:
25 => 25
25,1 => 25,10
25,10 => 25,10
25,12 = > 25,12
I have searched the forums but not found a matching question (here, here and here) and I have looked at the javadoc for BigDecimal and NumberFormat without understanding how to do this.
EDIT: Today I do:
NumberFormat currencyFormat02 = NumberFormat.getCurrencyInstance(locale);
currencyFormat02.setMinimumFractionDigits(0);
currencyFormat02.setMaximumFractionDigits(2);
currencyFormat02.setGroupingUsed(false);
BigDecimal bd = new BigDecimal("25 or 25,1 or 25,10 or 25,12");
String x =currencyFormat02.format(bd);
x should print as above but does not.
Probably not the most efficient but you could try something like this:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
class Main {
public static void main(String[] args) {
BigDecimal ex1 = new BigDecimal("25");
BigDecimal ex2 = new BigDecimal("25.1");
BigDecimal ex3 = new BigDecimal("25.10");
BigDecimal ex4 = new BigDecimal("25.12");
printCustomBigDecimalFormat(ex1);
printCustomBigDecimalFormat(ex2);
printCustomBigDecimalFormat(ex3);
printCustomBigDecimalFormat(ex4);
}
public static void printCustomBigDecimalFormat(BigDecimal bd) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("##.00", symbols);
if(containsDecimalPoint(bd)) {
System.out.println(df.format(bd));
} else {
System.out.println(bd);
}
}
private static boolean containsDecimalPoint(BigDecimal bd) {
return bd.toString().contains(".");
}
}
Output:
25
25,10
25,10
25,12
Try it here!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With