Converting a String to a Double, may I use Double constructor?

Hello,
I need to convert A String to a Double in my application.
Usually I use the Double.parseDouble(String) method that works fine.
But I have found one line in the code that use the Double class constructor: new Double(String). It has been observed that that constructor sometimes throws NullPointerException.
My question is, are theses two methods both good practices to do the convertion? Could threre be a multi-threading problem with the Double construtor?
I'm using JDK 1.3.1.
Here is a sample of stack trace:
bvsmgr: java.lang.NullPointerException
     at java.lang.FloatingDecimal.readJavaFormatString(Unknown Source)
     at java.lang.Double.valueOf(Unknown Source)
     at java.lang.Double.<init>(Unknown Source)
Thank you for all answers,
Florent.

But I have found one line in the code that use the
Double class constructor: new Double(String).
It has been observed that that constructor sometimes
throws NullPointerException.
My question is, are theses two methods both good
practices to do the convertion? Could threre be a
multi-threading problem with the Double construtor?Both methods are the same (they both use valueOf()), and if the c'tor throws an NPE, then only because you feed it null. parseDouble would do that, too.

Similar Messages

  • Converting a string to the corresponding value of type double

    Hey, im a really noob at this, but I need some help with this question. I've got to complete this in order to progress to my second year although im not doing programming and will not need it in the second year. The question is as follows:
    "Write a method called convertDouble as follows:
    public double convertDouble (String value) {
    This method should convert its parameter (a string like "3.1415") to the corresponding value of type double. If the string supplied is not a valid number, it should return 0.0 as its result. Note that you can use the method Double.parseDouble() to do the hard work for you. "
    To be honest I dont really have a clue what how to write this so any help would be much appreciated. Cheers guys

    Well the simplest way is to use Java's already inbuilt converter:
    which is if you have a string S which represents a double i.e 3.142
    You can use
    double number = Double.parseDouble(S); and thats it.
    The other way to do it is to loop through the string and check whether it is a number
    by using Character.IsDigit(ch) ? or somethign similar.
    and if it is a digit then subtract a fixed amount depending on its ASCII value.
    so if character with a value of 40 represents 0 (im not sure if it does) then
    any Digit character - 40 would give you the decimal value.
    Please ask questions if i dont make sense.
    Edited by: z0rgy on Aug 18, 2008 7:36 AM

  • Is it possible to convert from string to variant?

    Hi!
    I would like to convert a text string to variant. I'm doing this because I would like to merge a couple of signals and then save all the signals in a lvm-file. Could someone please explain how to convert from text to variant, is it possible?
    Thanks in advance!
    Regards,
    Mattias
    Attachments:
    Merge signals.JPG ‏27 KB

    What you are attempting to do is possible, but might not give you the results you expect.  All you need to do is convert your string to an array of U8s using the String to Byte Array conversion primitive.  In the file, you will get a single character per line of the file expressed as the ASCII code.  When you read it, convert to U8s, then use Byte Array to String to get your string back.
    You may also want to read up on LVM files.  There are several places to put strings that work a little better than this.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Convert a string to JAva.sql.date..

    I am having a string with the value as follows..
    String fval="03-10-2001"..
    I am using this value in a rs.updateDate method where I need to convert it to a different format as
    2001-10-03...can anybody give me the syntax..

    You should hold dates as Date instances. But if you want to convert between Strings and Dates then you should use a DateFormat:
    String originalDateString = "31-10-2001";
    // Convert the original string to a date
    DateFormat originalDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = originalDateFormat.parse(originalDateString);
    // Get a representation of the date in the new format
    DateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String newDateString = newDateFormat.format(date);(Excuse the quirky formatting that the Java code filter applies!)
    Hope this helps.

  • How can I convert a string to a seperated characters?

    How can I convert a string to a separated characters without using array?
    such as: input = String "word"
    output =
    w
    o
    r
    d
    Thanks

    A string is stored internally in individual characters.
    The String class has a method 'charAt(int index)' which returns the character at that index so using a for loop..
    String s = "word";
    for(int counter=0; counter < s.length(); counter++)
    System.out.println(s.charAt(counter));
    HTH

  • Converting a String to Date

    I have a String in which i am storing the date which I have retrieved from database. How can I convert this String to a Date object and use Comparator for sorting.
    String strCreatedDate1 = ((CVendorEmployees) vendoremployee1).getCreatedDate().toUpperCase();The date format which I will retrieve from String is mm/dd/yyyy.
    I want to convert this into date and use it for sorting.
    Thanx.

    Date dtTmp = new
    SimpleDateFormat("dd-MM-yyyy").parse(((CVendorEmployee
    s) vendoremployee1).getCreatedDate());
                                  Calendar calendar = Calendar.getInstance();      
                                  calendar.setTime(dtTmp);
    Now you have the date object do what ever you wish toBetter make thatnew SimpleDateFormat("MM/dd/yyyy")And no need for the Calendar stuff if all you want is a Date object.

  • Converting from string to double (formula)

    Hi All,
    I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
    double c = 35.0;
    String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
    The returned value of string res is (1.8*c)+32
    How do i make the above stmt to substitue value of c into above equation and returned me the result value.
    thx
    vinod

    vinod_kmr wrote:
    Hi All,
    I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
    double c = 35.0;
    String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
    The returned value of string res is (1.8*c)+32
    How do i make the above stmt to substitue value of c into above equation and returned me the result value.
    thx
    vinodas I understand you actually want to solve. if so, and res always returns that formula, then you can skip the properties file and just solve it already. something like:
    double result = (1.8*c) + 32.0if the result you are looking for is res with the value of the double substituted for c in the formula then the first step is to convert the the double c into a string and sticking that in res using String.replace(). something like
    res = res.replace("c", Double.toString(c));of course I don't know if String in android is like java.lang.String (same with Double) but I'm sure an equivalent exist.

  • How do you convert this String into a double?

    Hi, in this code I want to convert String arg into a double. I'm trying to do this so that I can convert some string into a double in this calculator that I'm making. Here is the code:
    public class par {
    public static void main(String[] args) {
    String str = "351";
    double arg = new double(str); // should convert the string into a double
         System.out.println(arg);
         System.out.println(str);
    I keep getting errors in line 4, if any of you could help me out here I'll be thankful, i'm kinda new to java and my search for java's equivalent of alof() (its a function in C libraries that converts char[] into a double)lead me to this.
    Tony L.

    Use the Following:
    String num = "123.2";
    double d = Double.parseDouble(num);

  • Returning a double (i.e.15.00) without converting to string

    i have an assignment which requires a method to return double to 2 decimals. i have a problem when the double ends in (i.e. 15.00)
    i can only get it to 1 decimal (i.e. 15.0). (drops unnecessary zeroes)the only way i can get it to 2 is to use the decimalformat class and convert to string. but the only problem is i need the method to return a double to keep profesor happy.
    the String version:
    public String totalFines()
    DecimalFormat nf = new DecimalFormat("####.00");
    double total=0.00;
    cursor=head;
    while(cursor != null)
    total+=cursor.getData().getFine();
    cursor = cursor.getNext();
    return nf.format(total);
    does anyone have any ideas???
    thanks
    -chris.

    i have an assignment which requires a method to return
    double to 2 decimals. i have a problem when the double
    ends in (i.e. 15.00)
    i can only get it to 1 decimal (i.e. 15.0). (drops
    unnecessary zeroes)the only way i can get it to 2 is
    to use the decimalformat class and convert to string.
    does anyone have any ideas???java.math.BigDecimal will do what you want:
    double d = 15.00;
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    System.out.println(bd.toString());

  • How do I convert a string to a double, a number loses the precision

    I tried converting a string to a double but that limits the precision. I need to convert a string to a double.

    If you use the Scan From String function, the default is to convert to a dbl. If you're looking at a front panel indicator, don't confuse the format and precision of the indicator with the type representation. You can set the indicator to display as many digits as you want but that doesn't change the actal number stored in memory.

  • Having trouble converting a string to a double

    Im having problems converting a string to a double in my jsp pages, i have pasted part of the code that is causing the problem. Just a note, i have imported the java.lang.* classes also
    while ( rs.next() )
    String price = rs.getString("price");
    sPrice = double.parseDouble(price);
    out.println("<TD>$" + decimalFormat.format(sPrice) + " </TD>");
    An error occurred at line: 140 in the jsp file: /cs399/AddToShoppingCart.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    C:\jakarta-tomcat-4.1.29\work\Standalone\localhost\_\cs399\AddToShoppingCart_jsp.java:277: class expected
              sPrice = double.parseDouble("price");
    ^

    double is a primitive. You want java.lang.Double, with a capital "D":
    sPrice = Double.parseDouble(price);MOD

  • "Property value is not valid" when PropertyGridView tries to convert a string to a custom object type.

    Hi,
    I have a problem with an PropertyGrid enum property that uses a type converter.
    In general it works, but when I double clicking or using the scoll wheel,  an error message appears:
    "Property value is not valid"
    Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
    I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
    Here is the code that causes the error (see line 33):
    (Using the .net symbols from the PropertyGridView.cs file)
    1
            internal bool CommitValue(GridEntry ipeCur, object value) {   
    2
    3
                Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");   
    4
    5
                int propCount = ipeCur.ChildCount;  
    6
                bool capture = Edit.HookMouseDown;  
    7
                object originalValue = null;   
    8
    9
                try {   
    10
                    originalValue = ipeCur.PropertyValue;   
    11
    12
                catch {   
    13
                    // if the getter is failing, we still want to let  
    14
                    // the set happen.  
    15
    16
    17
                try {  
    18
                    try {   
    19
                        SetFlag(FlagInPropertySet, true);   
    20
    21
                        //if this propentry is enumerable, then once a value is selected from the editor,   
    22
                        //we'll want to close the drop down (like true/false).  Otherwise, if we're  
    23
                        //working with Anchor for ex., then we should be able to select different values  
    24
                        //from the editor, without having it close every time.  
    25
                        if (ipeCur != null &&   
    26
                            ipeCur.Enumerable) {  
    27
                               CloseDropDown();   
    28
    29
    30
                        try {   
    31
                            Edit.DisableMouseHook = true;  
    32
    /*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/ 
    33
                            ipeCur.PropertyValue = value;   
    34
    35
                        finally {   
    36
                            Edit.DisableMouseHook = false;  
    37
                            Edit.HookMouseDown = capture;   
    38
    39
    40
                    catch (Exception ex) {   
    41
                        SetCommitError(ERROR_THROWN);  
    42
                        ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);  
    43
                        return false;  
    44
    I'm stuck.
    I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
    Thanks in advance,
    Eric

     
    Hi,
    Thank you for your post!  I would suggest posting your question in one of the MS Forums,
     MSDN Forums » Windows Forms » Windows Forms General
     located here:http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=8&SiteID=1.
    Have a great day!

  • How do I convert a string into a decimal

    I've been tryin to convert a string into decimal but I can't get it to work at all. I keep getting an exception.
    I've tried all of these:
    double myDouble = Double.valueOf(string).doubleValue();
    int myint = Interger.parseInt(string);
    float myfloat = Float.parseFloat(string);
    I can't get anything to work.
    That string i'm reading in is an array containing values with decimals. ex: -45.09348
    All the above work fine if there is no decimal, but fails when it comes to one.
    How do I go about doing this?
    Thanks!

    This works for me:String s = "-45.6789";
    double d = Double.parseDouble(s);
    System.out.println(d);Mark

  • Convert a String Mar 7, 2008 to date in yyyy-dd-mm format

    Hi,
    Please help me to Convert a String Mar 7, 2008 to date in yyyy-dd-mm format..
    have to store that Date in SQL Server date field in yyyy-dd-mm.
    Regards,

    I done this and got the desired result 2008-03-07. Thanks... know checking it with my code :)
    String ss = "Mar 7, 2008";
              //System.out.println(ss);
              try{
              SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
              Date date = dateFormat.parse(ss);
              System.out.println(date.toString());
              System.out.println(new java.sql.Date(date.getTime()));
              }catch(Exception ee)
                   ee.printStackTrace();
              } //endsEdited by: bunty_india on May 8, 2008 8:09 PM

  • Convert from String to float

    How do I convert from String to float?

    Hi,
    you can use a Double for example - assuming value is that string to parse
    float f;
    try { Double d = new Double(value); f = d.floatValue(); }
    catch (NumberFormatException e) { f = 0.0; } // error - string value could not be parsed
    // here use your float fHope, that helps
    greetings Marsian
    P.S.: the Double class is usefull for that, because you also can get intValue(), doubleValue() or longValue() out of it for example. The StreamTokenizer for example parses numbers also only to double.

Maybe you are looking for

  • CD cover popped off and I need to put it back on

    Does anyone have a how-to for this? The plastic cover of the CD drive popped off of a machine I just got from another work site and I would like to try to put it back on. I tried the obvious, but it didn't work. Ideas? TIA, Karen

  • Using command click to select file in lion causes them to open--why?

    Lately a lot of routine things have become (for lack of a better word) sensitive in Lion.  I send an email and in about one in three it sends a duplicate.  If I am trying to place edited text in an email or word document I cannot get the cursor place

  • Illumination bar when in walkman

    When playing a song in walkman player illumination bar lights up in two different colors at the same time.(middle LED in one color and other two in another color) Is it normal? Is it a problem with the LED? I think it is supposed to light up in one c

  • How to synchronize two scroll bars

    Hi there, Can anyone tell me how to go about to synchronize 2 JScrollPanes so that When the Scroll bar of the top Pane is moved, the scrollPane of the bottom pane also moves in sync. Thanks in advance.

  • Confirmed quantity at sales document without stock at storage

    Dear Gurus, Im having problems with availability check, when creating a sales document with a material without stock available system confirms quantity. Can somebody tell me where can i check in order to solve this error? Best regars J.