Rohit Pal
Rohit Pal

Reputation: 27

How to use DecimalFormater in java?

i am new to the java, iam facing an issue in my task with DecimalFormat

when i give integer number it should not have any decimals, if i give decimal number it should print decimal value

i used the DecimalFormater as below

DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance();
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.applyPattern("0");

System.out.println(decimalFormat.format(123456789.2569));

here it is printing without decimals. i replace my patern with decimalFormat.applyPattern("#.##");

in this case when i give 299 it is printing 3

but it should print 299 how to do it?

finally, if i give 265 it should be 265, if i give 265.36 it should be 265.36

Upvotes: 1

Views: 116

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

If you use the #.## pattern you will get only the first digit and the rest of your number will be treated as fraction digits.

And that explains why you got 3 when you inputed 299 because with this pattern 299 is treated as 2.99 and then rounded to 3.

So try to use this pattern instead:

decimalFormat.applyPattern("###.##");

For further information about it you can take a look at:

Upvotes: 1

Related Questions