Java Data Type How to - Format a double value within the toString() method (with respect to the decimal)








Question

We would like to know how to format a double value within the toString() method (with respect to the decimal).

Answer

import java.math.BigDecimal;
import java.text.DecimalFormat;
/*from  w  w w.  ja v a 2  s  .c o m*/
public class Main {
  public static void main(String[] args) {
    showPrice(new BigDecimal("123.456"));
    showPrice(new BigDecimal("11.12"));
    showPrice(new BigDecimal("10.5"));
    showPrice(new BigDecimal("1.5"));
    showPrice(new BigDecimal("0.5"));
  }

  static void showPrice(BigDecimal price) {
    DecimalFormat format = new DecimalFormat("0.00");
    String text = String.format("Price: $%5s", format.format(price));
    System.out.println(text);
  }
}