Skip to content
Advertisement

How to round and scale a number using DecimalFormat

I’m trying to to format a number using the DecimalFormat but the problem that I didn’t get the expected result. Here is the problem:

I have this number: 1439131519 and I want to print only the five first digits but with a comma after 4 digits like this: 1439,1. I have tried to use DecimalFormat but it didn’t work.

I tried like this but it dosen’t work:

 public static DecimalFormat format2 = new DecimalFormat("0000.0"); 

Anyone have an idea?

Advertisement

Answer

It is easier to do with maths rather than formatting.

Assuming your number is in a double:

double d = 1439131519;
d = d / 100000;      // d = 14391,31519
d = Math.round(d)    // d = 14391
d = d / 10;          // d = 1439,1

Of course, you can do it in one line of code if you want. In using Math.round I am assuming you want to round to the nearest value. If you want to round down you can use Math.floor.

The comma is the normal decimal separator in much of Europe, so that might work by default in your locale. If not, you can force it by getting the formatter for a locale such as Germany. See: How to change the decimal separator of DecimalFormat from comma to dot/point?.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement