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