import java.math.BigDecimal;
import java.text.DecimalFormat;
public class HelloWorld{
public static void main(String []args){
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("two decimals: " + new BigDecimal(df.format(123.435435))) ;
System.out.println("zero two decimal places: " + new BigDecimal(df.format(0.0000))) ;
System.out.println("zero without a decimal place: " + new BigDecimal(df.format(0))) ;
}
}
The output is:
three decimals: 123.44
zero two decimal places: 0
zero without a decimal place: 0
Now, DecimalFormat df = new DecimalFormat("#.##");
This is something that is used widely in my application and I do not, yet, have an option to modify this. How can I print 0 as 0.00 in the above program?
According to the Javadoc formatting with '#' will show zero as absent. You can use '0' instead to show a decimal place unconditionally, even if the digit concerned is zero.
Note that BigDecimals are used for calculations where high precision is required, e.g. financial applications. If you just need to print formatted numbers, you don't really need them.
With BigDecimals: