Search code examples
javadoubledecimalroundingdigits

How to keep n decimal places in Java


Hi All it might be a trivial question but as for now I could not find any solution.So asking for your help!

What I am trying to get is a specific encoding table that looks like this:

0.000
0.100
0.200

I need to keep track of zeroes as I will use them to reconstruct a part of an specific array. Original loop that was creating those numbers is:

for(int k=0;k<m_0;k++){
    for(int l=0;l<m_1;l++){
        for(int a=0;a<a1;a++){
            
            Y[x-1]=0.1*k+0.01*l+0.001*a;
            x++;
            
        }
        
    }
    
}

Problem! I could not fix zeros after decimal place and rather then getting table described above I am getting following:

0.0
0.1
0.2

As a solution I have tried to use BigDecimal and DecimalFormat but no success. Any suggestions?

UPD Few words what I am trying to do. I am encoding specific array to array and back index correspondence. For example 0.100 will be decomposed into 1 and 0 and 0 and used as array index labeling like:

Array1[Method(1,0,0,Y(i)][Method(1,0,0,Y(i))]=Array2[1][0][0]

So that I need an output suitable for assigning array index and string will not do the deal.


Solution

  • The DecimalFormat class is the correct place to look. You just need the correct format.

    DecimalFormat df = new DecimalFormat("0.000");
    System.out.println(df.format(0.1));
    

    Output:

    0.100