Faster, better AI-powered code reviews. Start your free trial! ย 
Faster, better AI-powered code reviews.
Start your free trial!

Get high quality AI code reviews

Java Decimal Format Example: Java Explained

Table of Contents

Java Decimal Format is the simplest way to format decimal numbers, often with a set of specific rules like how many decimal points to show and how to round the remaining decimal numbers. It’s built into Java and used to display numbers in many formats for different regions, such as currency and scientific notation. Decimal formatting is important for precision, which is why it’s so useful to know how to use it.

What is Java Decimal Format?

Java Decimal Format is a simple class used to display and format strings representing decimal numbers. It is part of the java.text package of Java. The class allows you to specify the desired number of digits to display when using one of the pre-defined standard formats (e.g. currency, percentage, etc). It also supports currency symbols, such as the euro or US dollar sign. The Java Decimal Format class is mainly used to format decimal numbers with specific precision.

The Java Decimal Format class also allows you to customize the format of the output string. You can specify the number of decimal places to display, the character used to separate the decimal places, and the character used to separate the thousands. You can also specify the currency symbol to be used in the output string. Additionally, the Java Decimal Format class provides methods to parse a string into a decimal number, and to convert a decimal number into a string.

Why Use Java Decimal Format?

Using Java Decimal Format provides great control over how decimal numbers are displayed in your program. It’s particularly useful for displaying numbers in different currencies, scientific notation, and for use in finance. Java Decimal Format allows you to limit the number of digits shown for most samples, which is beneficial for applications that need to save memory. Other advantages include formatting options based on a userโ€™s locale (language, region and currency), or changing the pattern of the number.

Java Decimal Format also allows you to easily round numbers to a certain number of decimal places. This is useful for applications that need to display numbers in a consistent format. Additionally, it can be used to display numbers in a variety of formats, such as percentages, fractions, and exponential notation. This makes it a great tool for displaying data in a variety of ways.

Syntax of Java Decimal Format

The syntax of the Java Decimal Format class is straightforward: new DecimalFormat(pattern). Here is an example of a pattern for formatting numbers: # ###.##. This pattern will display each number with a default size of three characters, followed by two decimal points or two zero digits. If the number is smaller than three characters, it will be padded with zero digits as necessary.

The pattern can also be used to format currency values. For example, the pattern $#,###.## will display the currency symbol followed by the number with a default size of three characters, followed by two decimal points or two zero digits. If the number is smaller than three characters, it will be padded with zero digits as necessary.

Creating a Java Decimal Format Object

The first step in using Java Decimal Format is to create a new instance using the syntax above. Once you’ve created a new instance, you can then use it to format any decimal number that you like. To do this, you use the format() method of the DecimalFormat class. This takes a double value and returns a formatted string representing its value. Here is an example of a DecimalFormat object being created and used to format a double value:

DecimalFormat df = new DecimalFormat("# ###.##");String formattedValue = df.format(1.234);// formattedValue = "1.23"

The DecimalFormat class also provides a parse() method which can be used to convert a formatted string back into a double value. This is useful for parsing user input and ensuring that it is in the correct format. For example, if a user enters a value of “1.23” into a text field, you can use the parse() method to convert it back into a double value.

Formatting Numbers with Java Decimal Format

Once you have created a Java Decimal Format object, you can then call its format() method to format a double-precision floating-point number into a String with the specified pattern. The most common pattern uses the sharp sign (#) to represent the minimum number of characters to be displayed, followed by a decimal point and then the number of decimal digits to be displayed. Here is an example showing how to use these patterns to display double values correctly:

DecimalFormat df = new DecimalFormat("# ####.##");String formattedValue1 = df.format(123.456);String formattedValue2 = df.format(12.345);String formattedValue3 = df.format(1.234);// formattedValue1 = "123.46"// formattedValue2 = "12.35"// formattedValue3 = "1.23"

In addition to the sharp sign (#), you can also use the zero sign (0) to represent the minimum number of characters to be displayed. This is useful when you want to ensure that the output is always the same length, regardless of the value of the number being formatted. For example, if you wanted to format a number with two decimal places, you could use the pattern “0.00” to ensure that the output is always two characters long.

Using the RoundingMode Enum with Java Decimal Format

Java Decimal Format supports various types of rounding methods through the RoundingMode enum. This enum specifies the rounding mode to use when you call the format() method. The most commonly used rounding mode is HALF_EVEN, which will round a value with a zero following the last digit so that it can fit into a specific pattern. Here is an example showing how this rounding mode can be used:

DecimalFormat df = new DecimalFormat("# ####");df.setRoundingMode(RoundingMode.HALF_EVEN);String formattedValue = df.format(123.456); // formattedValue = "123" 

Working with Currency in Java Decimal Format

The Java Decimal Format class also supports formatting of numbers as currency values. This is done by using the NumberFormat class which allows specific formatting rules to be set for different currencies. Here is an example showing how to set up a currency format:

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);String formattedCurrencyValue = currencyFormat.format(12345.67); // formattedCurrencyValue = "$12,345.67" 

Parsing Strings with Java Decimal Format

The Java Decimal Format class also supports parsing of strings into their numerical values by using the parse() method. This method allows you to parse a String and convert it into its numerical value with one line of code. Here is an example showing how this can be done:

DecimalFormat df = new DecimalFormat("# #####"); Number parsedNumber = df.parse("12345"); double parsedNumberValue = parsedNumber.doubleValue(); // parsedNumberValue = 12345 

Locale-Aware Number Formatting in Java Decimal Format

Java Decimal Format supports locale-specific formatting of numbers in order to make them locale-appropriate. This is done using the NumberFormat class, which allows users to set specific rules for formatting numbers in various locales (such as US currency, Indian currency or Arabic numbers). Here is an example showing how to create a new NumberFormat object that can be used for formatting numbers for a specific locale:

NumberFormat decimalFormat = NumberFormat.getInstance(Locale.FRANCE); String formattedNumber = decimalFormat.format(12345); // formattedNumber = "12ย 345,00" 

Conclusion

The Java Decimal Format class is a powerful tool for formatting and parsing decimal numbers in specific patterns that have been defined by the user. Its formatting capabilities are especially useful when dealing with currency values and scientific notation, while its parsing capabilities allow you to convert strings into their numerical values quickly and easily. Finally, it also supports locale-specific formatting so that numbers can easily be displayed in languages other than English.

Sarang Sharma

Sarang Sharma

Sarang Sharma is Software Engineer at Bito with a robust background in distributed systems, chatbots, large language models (LLMs), and SaaS technologies. With over six years of experience, Sarang has demonstrated expertise as a lead software engineer and backend engineer, primarily focusing on software infrastructure and design. Before joining Bito, he significantly contributed to Engati, where he played a pivotal role in enhancing and developing advanced software solutions. His career began with foundational experiences as an intern, including a notable project at the Indian Institute of Technology, Delhi, to develop an assistive website for the visually challenged.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Related Articles

Get Bito for IDE of your choice