开发者

Java default number to string behavior

I have two projects in my eclipse workspace which are having similar tasks. Both projects have a special part where I convert a double to an String.

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

In the older project I get the number always in a format like "-0.00097656" which is the format I need. In the newer one I get an tenth exponential format like "-9.765625E-4". I also have the fact that the old project cuts the string to be small enough.

My question is: Which commands can cause to this behavior that java changes the default conversion output. I already se开发者_如何学JAVAarched the code but I don't see something which does this. Or is it maybe an eclipse option?

I want to get the newer project consistent to 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 there must be a setting or some calls...

Hope somebody can give a hint.


It's clearly explained in the javadoc (see Double.toString()) - format depends on magnitude of number:

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

  • If m is less than 10-3 or greater than or equal to 107, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10n <= m < 10n+1; then let a be the mathematically exact quotient of m and 10n so that 1 <= a < 10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' ('\u002E'), followed by decimal digits representing the fractional part of a, followed by the letter 'E' ('\u0045'), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int).

If you want a specific format, use String.format() or something similar.


Try String.format(). And have a look at the Format String Syntax. This should help to get your doule into the format you want it.

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

Should do what you want.


Try this, digits is applied to the format precision, and you can have it a constant, if need be.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜