舍入双重或科学记数法

时间:2015-05-04 04:19:41

标签: java

如果长度超过8个字符,我想对我的号码进行舍入。 例如

//big number rounding using scientific notation
double myDouble1 = 123456789;// desired output: 1.23e+08

另一种情况

//rounding
double myDouble2 = 12345.5678901234;//desired output: 12345.57

我已尝试将String.format()%.2g%.7一起使用,但我无法达到所需的输出。

这是我尝试提出的代码。

 public String parseResult(String val){
    String formatted = val;
    try{
        if(formatted.length() > 8){
            double temp = Double.parseDouble(val);
            if(temp % 1 == 0){
                formatted = String.format("%.2g",temp);
            }else{
                formatted = String.format("%.7g",temp);
            }
        }
    }catch(NumberFormatException e){}
    return formatted;
}

2 个答案:

答案 0 :(得分:1)

public class SolutionMain
{
        public static void main(String[] args)
    {       
        double myDouble1 = 123456789;// desired output: 1.23e+08
        double myDouble2 = 12345.5678901234;//desired output: 12345.57

        System.out.println(parseResult(myDouble1));
        System.out.println(parseResult(myDouble2));
    }

    public static String parseResult(Double myDouble)
    {
        DecimalFormat format = null;

        if(myDouble.toString().length() > 8)
        {
            if(myDouble%1 == 0)
                format = new DecimalFormat("0.00E00");
            else
                format = new DecimalFormat("#.00"); 
        }

        return format.format(myDouble);
    }
}

有关更多模式格式的详细信息:Customizing Formats

答案 1 :(得分:-1)

class ScientificNot
{

      public static String getScientifiNotation(double n)
    { 
          int n1=(int)n;
          String s0=String.valueOf(n-(double)n1);
          String s1=String.valueOf((double)((int)n));
          int in=s1.indexOf(".");     
          String mantissa=null,exp=null;
          if(n>=10000000.0)
          {

             if(s1.length()>8)
             {
                  mantissa=s1.substring(0,3);
                  exp=s1.substring(3);
                  double man=Double.parseDouble(mantissa)/100.0;
                  return(man+"e"+exp.length());

                 }
             else
             return s1;
           }
          else if(s0.length()>8)
             {
               double num=(((double)((int)(n*1000)))); 
               int dp=((int)num%1000);
               if(dp%10>=5)
                      dp=(dp-(dp%10))+10;
               return String.valueOf(((int)num/1000)+"."+(dp/10));
               }
              else{
                 s1=""+n;

              }   
          return s1;
        }
    }