Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Floating point number in java upto 3 precison of decimal

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..

like image 763
Abhay Avatar asked Aug 30 '13 05:08

Abhay


1 Answers

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)
like image 169
Tarsem Singh Avatar answered Sep 28 '22 15:09

Tarsem Singh