Java NumberFormat format double as currency

Description

Java NumberFormat format double as currency

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

public class Main {

   public static void main(String[] args) {
      // Run the currency calculation examples
      BigDecimal currencyOne = new BigDecimal("225.65");
      BigDecimal currencyTwo = new BigDecimal("187.32");
      BigDecimal currencyThree = new BigDecimal("24.86");
      BigDecimal result = null;//from w w w .ja v a2 s .  c o  m
      String printFormat = null;

      // Add all three values
      result = currencyOne.add(currencyTwo).add(currencyThree);
      // Convert to double and send to formatDollars(), returning a String
      printFormat = formatDollars(result.doubleValue());
      System.out.println(printFormat);

      // Subtract the first currency value from the second
      result = currencyTwo.subtract(currencyOne);
      printFormat = formatDollars(result.doubleValue());
      System.out.println(printFormat);
   }

   /**
    * Formats a double value into currency format and then returns it as a String
    * 
    * @param value
    * @return
    */
   public static String formatDollars(double value) {
      NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(Locale.US);
      return dollarFormat.format(value);
   }

}



PreviousNext

Related