Reputation: 697
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..
Upvotes: 5
Views: 12821
Reputation: 14199
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)
Upvotes: 7
Reputation: 10632
Try formatting as below :
DecimalFormat df = new DecimalFormat();
df.applyPattern(".000");
System.out.println(df.format(f));
Upvotes: 3
Reputation: 1527
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
Upvotes: 2
Reputation: 41271
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.
Upvotes: 1