2

I have double values in Java like the following:

2.3422
45.3267
25.0

What I want to print is:

2.34
45.32
25

So I used the following method

DecimalFormat form=new DecimalFormat("#0.00");
form.format(value);

But the problem I am facing is for 25.0 it is printing 25.0 But I want to print 25 only what do i do?

Please note that casting the double value to integer would work for 25.0 but then it would fail for values like 2.3422.

Andreas
  • 154,647
  • 11
  • 152
  • 247
J J
  • 165
  • 6

3 Answers3

5

try to use this format: "#0.##"

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
2

Use this.

DecimalFormat form = new DecimalFormat("0.##");
System.out.println(form.format(2.3422));
System.out.println(form.format(45.3267));
System.out.println(form.format(25.0));

output :
2.34
45.33
25

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
1

Fix your code to:

DecimalFormat form = new DecimalFormat("#0.##");

Or you can either use:

double value = 123.456789;
String.format( "%.2f", value );
The Dr.
  • 556
  • 1
  • 11
  • 24