Tuesday, December 10, 2024
HomeComputer programmingJava programmingJava: Decimal Format to Create Custom Output Easily

Java: Decimal Format to Create Custom Output Easily

The Decimal Format class is a poorly explained class in the Java Documentation, so I will clear up a little of it with an example.


You first need to import the DecimalFormat class:

import java.text.DecimalFormat;

Then create a format object. This object can be used with doubles, as it uses a decimal. It uses a template String to teach Java how to ouput the objects.
*This example will be used as a standard format of money:

DecimalFormat money = new DecimalFormat("$0.00");

Now that you have a money object (declared either globally or locally) you can now format your objects.
*Note: This example uses only two decimal places and a $, but any symbols or length is available.

As an example of printing a double value:

double amount = 4.333333333;
System.out.println(money.format(amount));

What will be printed is $4.33 as described by the template. This handles your precision and dollar sign with a single template.

Questions/Comments: [email protected]
-William. § (marvin_gohan)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!