Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Empowering you to understand your world

How To Format A Decimal Number In Android (Java)

If you’re developing an Android app that displays floating point numbers or use the ‘double’ data type, you might encounter an unpleasant long trail of digits after your decimal place that you don’t need.

Using the ‘DecimalFormat‘ class in Java enables you to round numbers off to your preferred number of decimal places. You can format your floating point number for a high degree of precision if working with tiny numbers, or you can round it to 2 decimal places for larger numbers.

The first step is to create a DecimalFormat object. We will name this example ‘dform’:

DecimalFormat dform = new DecimalFormat("#.####");

Afterwards, use that new object to format your number (your number in this case would be ‘yourDouble’):

dform.format(yourDouble);

The ‘dform.format’ code above will return a String containing the formatted version of ‘yourDouble’.

If you want to format a number to include commas in Android, you can just replace the dot with a comma as shown below:

DecimalFormat dform = new DecimalFormat("#,###.####");

Or:

DecimalFormat dform = new DecimalFormat("#,###.99");

There are countless different ways to do it, with varying effects. Test your app carefully after trying any of these to ensure it formats it in the way that you intended!

Subscribe to our newsletter
Get notified when new content is published