0

I require a DecimalFormat or a better equivalent of representing a Double value (in Java) which could be:

25 or 25.5

I need for that to be represented as either a whole number (25) or to two decimal places if it has any (25.50). This is because i'm printing it out as money.

I have the following format already:

DecimalFormat decFormat = new DecimalFormat("##,###.##");

This works perfectly if the Double is a whole number; I get the output $25,000. Except if the value is 25,000.5; it prints $25,000.5 when I need it to be printed as $25,000.50. The problem is as stated in the docs:

# a digit, zero shows as absent

So essentially the last zero is dropped off since it is optional.

I cannot do:

DecimalFormat decFormat = new DecimalFormat("##,###.#0");

as that is not allowed.

How can I achieve this?

Note: These questions are related but do not cover what I need specifically with the DecimalFormat. Most of the answers suggest using a BigDecimal or printf. Is this the best thing to do? I don't have to use DecimalFormat but prefer to since i've started on that path (lots of code everywhere already using it).

Best way to Format a Double value to 2 Decimal places

How do I round a double to two decimal places in Java?

Round a double to 2 decimal places

Community
  • 1
  • 1
Möoz
  • 847
  • 2
  • 14
  • 31
  • did you try `new DecimalFormat("##,###.00");`? – ajb Mar 18 '14 at 01:42
  • Yes that gives me two decimal places regardless of the Double having one or not. i.e 25000 becomes 25,000.00 which I do not want – Möoz Mar 18 '14 at 02:15

2 Answers2

2

This is definitely a bit of a hack, but I don't know if the DecimalFormat syntax allows for anything better. This simply checks to see if the number is real, and formats based on the spec you asked for.

    double number = 25000.5;
    DecimalFormat df;

    if(number%1==0)
         df = new DecimalFormat("##,###");
    else
        df = new DecimalFormat("##,###.00");

    System.out.println(df.format(number));
Azar
  • 1,086
  • 12
  • 27
0

When you need to return Decimal Format value this works

import java.text.DecimalFormat;

/**
* @return The weight of this brick in kg.
*/
public double getWeight()
{

    DecimalFormat df = new DecimalFormat("#.##");

    double number = ( getVolume() * WEIGHT_PER_CM3 ) / 1000;

    //System.out.println(df.format(number));

    return Double.valueOf ( df.format( number ) ); 

}
Conor
  • 494
  • 6
  • 15