5

I have a variable type float.I wanted to print it upto 3 precision of decimal including trailing zeros.

Example :

2.5 >> 2.500

1.2 >> 1.200

1.3782 >> 1.378

2 >> 2.000

I am trying it by using

DecimalFormat _numberFormat= new DecimalFormat("#0.000");
Float.parseFloat(_numberFormat.format(2.5))

But it is not converting 2.5 >> 2.500.

Am I doing something wrong..

Please help..

Abhay
  • 687
  • 4
  • 13
  • 22
  • 2
    Why are you calling `Float.parseFloat` on the output? – user2357112 Aug 30 '13 at 05:16
  • The output of _numberFormat.format(2.5) is string and I need to set this new formatted value in another float variable before printing it..that's why I am calling Float.parseFloat... – Abhay Aug 30 '13 at 05:39
  • A `float` is just a number. It doesn't have any information about how many digits you want to use when you display it. Only the string representation has that information. – user2357112 Aug 30 '13 at 05:48

4 Answers4

7

Here is mistake Float.parseFloat this is converting back to 2.5

Output of _numberFormat.format(2.5) is 2.500

But this Float.parseFloat makes it back to 2.5

So your code must be

DecimalFormat _numberFormat= new DecimalFormat("#0.000");
_numberFormat.format(2.5)
nanofarad
  • 40,330
  • 4
  • 86
  • 117
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
3

Try formatting as below :

DecimalFormat df = new DecimalFormat();
df.applyPattern(".000");
System.out.println(df.format(f));
Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46
2

Try

System.out.printf("%.3f", 2.5);

The printf-Method allows you to specify a format for your input. In this case %.3f means

Print the following number as a floating point number with 3 decimals

Vince
  • 1,517
  • 2
  • 18
  • 43
1

You're writing a decimal to a formatted string then parsing it into a float.

Floats don't care if they read 2.500 or 2.5, although the former is formatted.

The float is not going to hold trailing zeroes as IEEE754 cannot handle specifying the number of significant fihgures.

nanofarad
  • 40,330
  • 4
  • 86
  • 117