J2ME - How to convert double to string without the power to 10 representation (E-05)

拈花ヽ惹草 提交于 2019-12-04 03:20:48

问题


I have a double value . I want to store it in String with out E notation (in J2ME)

Example

Double value 6.887578324E9 Want to show as 6887578342


回答1:


You can create your own method to do that, or use some already existing library. Javolution, for example, gives you the class and method TypeFormat.format(double d, int digits, boolean scientific, boolean showZero, Appendable a) Check Javolution, it has lots of nice utilities, but if the only thing you need is to format numbers, just write your own method. Here is a quick hack for big numbers

    private static String nosci(double d) {
    if(d < 0){
        return "-" + nosci(-d);
    }
    String javaString = String.valueOf(d);
    int indexOfE =javaString.indexOf("E"); 
    if(indexOfE == -1){
        return javaString;
    }
    StringBuffer sb = new StringBuffer();
    if(d > 1){//big number
        int exp = Integer.parseInt(javaString.substring(indexOfE + 1));
        String sciDecimal = javaString.substring(2, indexOfE);
        int sciDecimalLength = sciDecimal.length();
        if(exp == sciDecimalLength){
            sb.append(javaString.charAt(0));
            sb.append(sciDecimal);              
        }else if(exp > sciDecimalLength){
            sb.append(javaString.charAt(0));
            sb.append(sciDecimal);
            for(int i = 0; i < exp - sciDecimalLength; i++){
                sb.append('0');
            }
        }else if(exp < sciDecimalLength){
            sb.append(javaString.charAt(0));
            sb.append(sciDecimal.substring(0, exp));
            sb.append('.');
            for(int i = exp; i < sciDecimalLength ; i++){
                sb.append(sciDecimal.charAt(i));
            }
        }
      return sb.toString();
    }else{
        //for little numbers use the default or you will
        //loose accuracy
        return javaString;
    }       


}



回答2:


Have a look at this article: Converting Double to String without E notation

You can make use of the [NumberFormat][2] or [DecimalFormat][3] class to acheive what you are looking for.

Here is the code:

NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
String refinedNumber = f.format(doubleVariable);



回答3:


You can use Java Formatter, just specify how many decimals do you want with the string.

E.g. a double converted to a number with one decimal:

Formatter format = new Formatter();
String mystring = format.formatNumber(DOUBLENUMBERVARIABLE,1);
System.out.println(mystring );



回答4:


Normally you can use piece of code below, but not for j2me.

BigDecimal.valueOf(doubleVariable)


来源:https://stackoverflow.com/questions/5287716/j2me-how-to-convert-double-to-string-without-the-power-to-10-representation-e

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!