3

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.

Community
  • 1
  • 1
user1329339
  • 1,295
  • 1
  • 11
  • 26

3 Answers3

3

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!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

You then need to distinguish between BigDecimal values that represent "whole numbers"; and those that do not.

Something like:

BigDecimal someNumber = ...
if (someNumber.toBigIntegerExact()) {
 // go for the 25 kind of formatting
} else {
 // go for the 25.xx kind of formatting

The "25.xx" formatting is nicely described here ( or in the other answer by Leonardo )

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

To format BigDecimal with NumberFormat, you need to set Locale first, try something like this:

String strToFormat = "25.10";
Locale loc = new Locale("en","US");

DecimalFormat numFormat = (DecimalFormat)NumberFormat.getInstance(loc);
numFormat.setParseBigDecimal(true);
BigDecimal yourValue = (BigDecimal)numFormat.parse(strToFormat, new ParsePosition(0));

System.out.println("Value : " + yourValue);

Result :

Value : 25.10