Java default row by row

I have two projects in the eclipse workspace that perform similar tasks. Both projects have a special part in which I convert doubleto String.

I have both projects, I did this by calling String.valueOf(var).

In an older project, I always get the number in the format “-0.00097656” that I need. In the new version, I get the tenth exponential format, for example, "-9.765625E-4". I also have the fact that the old project reduces the length of the string.

My question is: what commands can lead to such behavior that java changes the default output. I have already searched for the code, but I do not see what does this. Or could it be an eclipse variant?

I want the new project to be consistent with the older one, and I don't want to use these string format calls every time in the new project. Anywhere in the old project should be setting up or some challenges ...

Hope someone can give a hint.

+5
source share
3 answers

This is clearly explained in javadoc (see Double.toString()) - the format depends on the size of the number:

  • If m is greater than or equal to 10 -3 but less than 10 7 then it is represented as the integer part of m, in decimal form without leading zeros, followed by '.' ('\ u002E') followed by one or more decimal digits representing the fractional part of m.

  • m 10 -3 10 7 " ". " n - , , 10 n <= m < 10 + 1; - 10 n 1 <= a < 10. a, , ".". ('\ u002E'), , a, 'E' ('\ u0045'), n , Integer.toString(int).

, String.format() - .

+6

String.format(). . doule , .

String.format("%1$f",var);

, .

+1

Try it, it digitsapplies to the accuracy of the format, and if necessary you can have a constant.

public static String formatDouble(double d, int digits){
    String s = String.format(Locale.US, "%."+digits+"f", d);
    if (s.indexOf('.')<0)
        return s;

    int last = s.length();                  
    while (s.charAt(--last)=='0');
    return s.substring(0,last+1);       
}
0
source

All Articles