3

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.

Community
  • 1
  • 1
madbitloman
  • 816
  • 2
  • 13
  • 21
  • 2
    The DecimalFormat class seems the way to go as described below. Could you post what you're trying to do so that we can see why it failed? – Jeff Wang Apr 02 '14 at 23:07
  • Hi Jeff, I have described in the Update section what I am trying to achieve. I am trying to get later from those .100 array elements like 1,0 and 0. That is why floating zero is crucial. – madbitloman Apr 03 '14 at 03:55

3 Answers3

8

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
rgettman
  • 176,041
  • 30
  • 275
  • 357
2

As an alternative to the DecimalFormat class, I would like to propose the following (which I use quite regularly):

Step 1: Create a function that allows me to specify the number of units to keep. Here is a copy of this function.

public static String format(Number n) {
        NumberFormat format = DecimalFormat.getInstance();
        format.setRoundingMode(RoundingMode.FLOOR);
        format.setMinimumFractionDigits(0);
        format.setMaximumFractionDigits(2);
        return format.format(n);
    }

Step 2: Call the function whenever you have any output to format. Below is a simple example using this function to set the appropriate decimal place length:

System.out.println("Based on this, the wind chill index was calculated to be " + format(chill));    

Note that you could simply change the line:

format.setMaximumFractionDigits(2);

to

format.setMaximumFractionDigits(n);

depending on your desired decimal length.

Nathaniel Payne
  • 2,749
  • 1
  • 28
  • 32
2

When you are printing the numbers, you can use this:

System.out.format("%.3f", yourDecimalNumber);
adam
  • 240
  • 1
  • 7