How to Format to Dollars in Java


Computer software has many real-world applications, such as providing an online marketplace for goods and services. Modern languages acknowledge these real-world applications using built-in techniques for tackling common tasks. For example, Java offers a method for converting between regular number types and currency number types. This is very convenient for programmers who develop online storefronts or accounting software. If your program deals with currency, familiarize yourself with the Java BigDecimal class.

Things You'll Need

  • Java Development Kit and Netbeans Bundle (see Resource)
  • Load the Java development environment by clicking on the NetBeans icon. Navigate to "File/New Project" in the top menu and choose "Java Application." A new source code file appears in the main editor window.

  • Import Java Math, Text, and Util libaries by writing these lines of code at the top of the source code file:

    import java.math.*;

    import java.text.*;

    import java.util.*;

  • Define a BigDecimal object by writing the next line of code between the curly brackets of the main function:

        BigDecimal cost = new BigDecimal("1120304.73");
  • Create a NumberFormat object named "Dollars" and assign the U.S. currency type to it. To do this, write this line of code:

        NumberFormat dollars = NumberFormat.getCurrencyInstance(Locale.US);
  • Create a string of text and assign the BigDecimal variable "Cost" to it. Since the cost variable needs to be properly formatted to the U.S. currency type, you can run the format function at the same time you assign it to the string, like this:

        String s = dollars.format(cost);
  • Print out the string like this:

  • Run the program by pressing "F6." The output looks like this:


Related Searches


Promoted By Zergnet



You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!