Existing String to Double

2019-03-05 12:01发布

问题:

How can I change existing string into double. I have code like this declared as string but in reality its getting number from the database.. I was doing sting to number conversion but now i dont wanna convert it as string and get it all the way as number

 private String _example1;

_example1 = new String();

public String getExample1() {
        return _example1;
    }

    public void setExample1(String s) {
        _example1 = s;
    }

so i just changed the String word with double in the above code..

private Double _example1;

    _example1 = new Double();

    public Double getExample1() {
            return _example1;
        }

        public void setExample1(Double s) {
            _example1 = s;
        }

but i am getting this error

[exec] com\sample\jack\javabean\ExampleBean.java:48: cannot resolve symbol
     [exec] symbol  : constructor Double ()
     [exec] location: class java.lang.Double
     [exec]             _example1 = new Double();
     [exec]                                 ^

[exec] com\sample\jack\javabean\ExampleBean.java:134: setExample1(java.lang.Double) in com.sample.jack.javabean.ExampleBean cannot be applied to (double)
     [exec]                             this.setExample1(cstmt.getDouble(2));
     [exec]                                 ^

Can someone tell me what I have to do to get it right.. Thank you

回答1:

Double is immutable and must be constructed with a value (there is not a no-arg constructor): http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html



回答2:

try {
  double d = Double.parseDouble(str);
  Double D = new Double(d);
}
catch( NumberFormatException e ) {
   // input cleansing
   // thou shalt not fail silently
}

Reference:

Double.parseDouble



回答3:

Just initialize it in your declaration, and remove the line where you set it to a new object. Take a look at this.



回答4:

I don't quite get your problem, but here are a few notes:

  • you can create a double by simple declaring double d = 0. Or new Double(0) (passing the double value as argument)
  • if you want to convert from string to double, use Double.parseDouble(string)