Double.parseDouble(String) - problems when string is in scientific notation

Hello guys,
I'm doing some numerical calculations and I wonder whether it is possible for Double.parseDouble(String) to parse string in the scientific notation i.e. 1.0824234234E-10. Is it the notation itself causing the exception : NumberFormatException or the number is just too big/small and double can't hold it ?
If it's just the notation how can I fix it ?
Regards

i'm not quite sure whether double odoes not allow it.
perhaps consider the api Double.valueOf() and the testing code provided; reproduced below:To avoid calling this method on a invalid string and having a NumberFormatException be thrown, the regular expression below can be used to screen the input string:
        final String Digits     = "(\\p{Digit}+)";
  final String HexDigits  = "(\\p{XDigit}+)";
        // an exponent is 'e' or 'E' followed by an optionally
        // signed decimal integer.
        final String Exp        = "[eE][+-]?"+Digits;
        final String fpRegex    =
            ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
             "[+-]?(" + // Optional sign character
             "NaN|" +           // "NaN" string
             "Infinity|" +      // "Infinity" string
             // A decimal floating-point string representing a finite positive
             // number without a leading sign has at most five basic pieces:
             // Digits . Digits ExponentPart FloatTypeSuffix
             // Since this method allows integer-only strings as input
             // in addition to strings of floating-point literals, the
             // two sub-patterns below are simplifications of the grammar
             // productions from the Java Language Specification, 2nd
             // edition, section 3.10.2.
             // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
             "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
             // . Digits ExponentPart_opt FloatTypeSuffix_opt
             "(\\.("+Digits+")("+Exp+")?)|"+
       // Hexadecimal strings
       "((" +
        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "(\\.)?)|" +
        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
        ")[pP][+-]?" + Digits + "))" +
             "[fFdD]?))" +
             "[\\x00-\\x20]*");// Optional trailing "whitespace"
  if (Pattern.matches(fpRegex, myString))
            Double.valueOf(myString); // Will not throw NumberFormatException
        else {
            // Perform suitable alternative action
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html

Similar Messages

  • Double.parseDouble(String) : Problem to parse large String

    Hello,
    I need to convert A String to a Double in my application without rounding of digits.
    I have used the Double.parseDouble(String) method.
    The maximum string length can be 17 including dot(.)
    So if my String is (of length 17)
    Eg.
    S= �9999999999.999999� then I am getting the double value as
    d= 9999999999.999998(compare the last digit)
    If s = �9999999999.111111� then d = 9999999999.111110
    If s = �9999999999.555555� then d = 9999999999.555555 (result that I want)
    If s = �9999999999.666666� then d = 9999999999.666666 (result that I want)
    If s = �9999999999.777777� then d = 9999999999.777777 (result that I want)
    If s = �9999999999.888888� then d = 9999999999.888887
    If s = �9999999999.999999� then d = 9999999999.999998
    If s = �9123456789.123456� then d = 9123456789.123456
    But string length up to 16 is giving me the accurate result
    So any body can explain me that why it is happening? And how can i get the accurate result.
    Thanks in advanced.

    Hi,
    Thank You for your suggestion. By which i can store
    the big double number in Data base , but at some
    point i require to parse a double value from a Double
    reference.In that case if the Decimal value length
    => 16 then it the last digit changes or rounds.
    coverting 9999999999.999999 Decimal value to double
    value. It gives me 9999999999.999998 and
    9999999999.9999999 gives me the 10000000000.0000000.
    but the Double value 999999999.999999 is ok
    and 999999999.99999999 rounds.Err, is there a follow up question in there?

  • Problem: program outputs numbers in scientific notation

    my problem is that my program outputs the population in scientific notation instead of round the number to the nearest one. ex: it should say 30787949.57 instead of 3.078794957 E7
    // Calculates the poulation of Mexico City from 1995 to 2018.
    // displays the year and population
    class PopulationCalculator {
    static double r2(double x) {
         //this method rounds a double value to two decimal places.
    double z=((double)(Math.round(x*100)))/100;
    return z;
    } //end method r2
    public static void main(String args[]) {
         double population=15600000.0;
         double rate=0.03;
         System.out.println("Mexico City Population, rate="+r2(rate));
         System.out.println("Year    Population");
         for (int year=1995; year<=2018;year++)  {
             System.out.println(year+ "    "+r2(population));
        population+=rate*population;
        }//end for loop
        System.out.println("The population of Mexico City reaches 30 million on 02/13/17 at 5:38:34am");
        }//end main
        }//end PopulationCalculator
    {code/]

A: problem: program outputs numbers in scientific notation

Or upgrade to JDK 5.0 and user the new java.util.Formatter capability.
You control the rounding and get localization of the fomatted string at
no extra charge. A quick example:
class A {
    public static void main(String[] args) {
        double d = 30787949.57d;
        System.out.println(java.lang.String.format("%,17.2f", d));
}Example output for three different locales:
$ javac -g A.java
$ LC_ALL=fr_FR   java A
    30 787 949,57
$ LC_ALL=en_NZ   java A
    30,787,949.57
$ LC_ALL=it_IT     java A
    30.787.949,57For more information, refer to:
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#formatter

Or upgrade to JDK 5.0 and user the new java.util.Formatter capability.
You control the rounding and get localization of the fomatted string at
no extra charge. A quick example:
class A {
    public static void main(String[] args) {
        double d = 30787949.57d;
        System.out.println(java.lang.String.format("%,17.2f", d));
}Example output for three different locales:
$ javac -g A.java
$ LC_ALL=fr_FR   java A
    30 787 949,57
$ LC_ALL=en_NZ   java A
    30,787,949.57
$ LC_ALL=it_IT     java A
    30.787.949,57For more information, refer to:
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#formatter

  • How let labview to verify string is in Scientific Notation.

    Hey all,
    I want labview to convert a spreadsheet string to an array. This is easy using the 'spreadsheet string to array' tool. The only problem I've got is that I get the string from a RS232 device and it is time critical.
    Example:
    If I read the data from the buffer it gives me:
    +1.50337800E+00,+1.70316300E+00 for two channels, this is converted and accepted
    if there is a small delay I get:
    +1.50337800E+00,+1.70316
    This will also be accepted because +1.70316 is also recognized as a number.
    How can program labview to check that every number it reads is according to the Scientific Notation?
    Thanks
    Solved!
    Go to Solution.

    Don_Phillips wrote:
    This regex seems to work for me for all the cases I tried:
    [+/-]\d+\.\d+[Ee][+/-]\d+
    Note that it is very restrictive and only follows the form of ±n.nnnE±mm
    If it was up to me, I'd fix the problem and not the symptom - but many times, it is NOT up to me.  MANY times there are artificial constraints (like the time allocated to fix the problem) so you just have to make a band-aid like this.  I get grumpy when I'm forced to program a workaround instead of a fix. 
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • Double.parseDouble() is not Locale specific, how do I get round this?

    I am parsing Strings into doubles using
    String myNumber = "12,34";
    double d = Double.parseDouble( myNumber );The problem is that my number is of French style (it has commas instead of fullstops for the decimal points)
    The default Locale is English, so I get NumberFormat problems when parsing. (I can understand this)
    I even get NumberFormat problems when I do this:
    Locale.setDefault(Locale.FRENCH);
    double d = Double.parseDouble( myNumber );Which I think is really strange. I guess the Locale of Double is set at a certain time and not reset.
    OR maybe Double.parseDouble( <STRING> ); is not Locale specific?
    Where is my understanding wrong?

    Do you know if DecimalFormat reflects the default Locale if the default Locale changes?
    Or will I have to make a new DecimalFormat whenever it changes?As Locale is invariant, a DecimalFormat instance (as well a any object with a reference to the default Locale) cannot reflect the default Locale changes.
    But each time you create a new instance of DecimalFormat without specifying the Locale, it will get up-to-date Locale.
    However, you might prefer setting the locale explicitely (instead of changing the default one.)
    Note that Double valueOf() or parseDouble() methods are not related to default Locale, they use a fixed format.

  • Problem when inserting "Thai language" string to MS Access with JSP

    Dear sir,
    I have the problem when try to insert "Thai langusge" string to MS access database through JDBC in JSP page.
    The JSP page is shown in the following.
    <HTML><HEAD><TITLE>Personalt Information</TITLE>
    <%@ page contentType="text/html; charset=MS874" %>
    <%@ page import = "java.io.*" %>
    <%@     page import = "java.lang.*"%>
    <%@     page import = "java.sql.*"%>
    <%
              Connection dbconn,conn;
              ResultSet results;
              String sql;
              Statement stmt;
              // Creating a conection with a database
              String url = "jdbc:odbc:bg3hrDB"; // the database file.
              //Statement stmt;
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   dbconn = DriverManager.getConnection(url);
                   stmt = dbconn.createStatement();
                   ResultSet rs;
    %>               
    %>
    <%
              String code=new String(request.getParameter("code").getBytes("ISO8859_1"),"MS874");
              String status=new String(request.getParameter("status").getBytes("ISO8859_1"),"MS874");
                   String fname=new String(request.getParameter("fname").getBytes("ISO8859_1"),"MS874");
                   sql = "INSERT INTO employee VALUES (' "+ code +" ',' "+ status +" ',' "+ fname +" ')";
    stmt.executeUpdate(sql);
    %>
    <%=fname%> //In this line, "fname" can show "Thai" correctly
    But after inserted to database, the record in Access was always show "?????" instead of "Thai"......
    How can i solve this?
    Thank you for your kindness in advances.
    Yongyos K.

    It's a pain in the butt, but you'll have to write your own character set conversion to handle the problem. Check out the link shown below (just replace BIG5 in the example with MS874):
    http://www.geocities.com/siufai6/java/JDBC_Chinese.html
    ;o)
    V.V.

  • Converting double to strings

    I'm having a problem in getting my double to convert to a string, here's my code so far.
         public void calculatePayments()
              double paymentAmount;
              double monthlyInterestRate = (Double.parseDouble(interestBox.getText())/12)/100;
              double amountOfLoan = Double.parseDouble(balanceBox.getText());
              double numberOfPayments = Double.parseDouble(yearsBox.getText()) * 12;
              paymentAmount = (amountOfLoan * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate),numberOfPayments));
              Double.toString(paymentAmount);
              tableBox.append(paymentAmount);
    And here's the error message I get:
    ProgramInterface.java:134: append(java.lang.String) in javax.swing.JTextArea cannot be applied to (double)
              tableBox.append(paymentAmount);
    As always, help is appreciated.

    This line returns a String but has no affect on paymentAmount.
    Double.toString(paymentAmount);To covert the double to String you can save the return in a variable
    String s = Double.toString(paymentAmount);
    tableBox.append(s);or combine them
    tableBox.append(Double.toString(paymentAmount));

  • Kinda urgent    please help pass strings to doubles and strings to ints

    Need to know how to pass strings to doubles and strings to ints
    and to check if a string is null its just if (name == null;) which means black right?
    like size as a string and then make the string size a double

    cupofjava666 wrote:
    Need to know how to pass strings to doubles and strings to ints
    and to check if a string is null its just if (name == null;) which means black right?
    like size as a string and then make the string size a doubleThink he means blank.
    Check the Wrapper classes (Double, Integer) in the api.
    parseInt() parseDouble() both take a string and return a primitive.
    String s = null;
    if(s == null) should do the trick!
    Regards.
    Edited by: Boeing-737 on May 29, 2008 11:08 AM

  • Trouble converting "double like" string to integer

    Hi everyone,
    I have a trouble here. Let's say I have a string which its value is "314.12345667". the value is "like a double". How do i convert it into an integer where the integer only takes the value of da string before the decimal point (as in the value of string = 314 only)? Thanks for helping.

    hi xamule,
    tey this..
    String s="314.123876"
    double d=Double.parseDouble(s);
    int x=d.intValue();
    hope it may help u..
    bye bye,
    Pramod

  • Calculating double from String

    Hello again
    I just have a quick question here, that confused me a bit (though I guess it makes sense)
    If I try to print the double 1 + 2 * 3, it will output 7.
    But I have a JTextField with the string 1 + 2 * 3, and I try to parse it as a double, it won't let me.
    Am I doing something since it doesn't work? To me it seems logic that it should be able to parse a string as a double, if it can calculate the double without a problem.
    Do you have any ideas?
    Any help here is appreciated
    Thanks in advance
    Ulverbeast
    Edited by: Ulverbeast on Feb 25, 2010 1:07 PM

    Ulverbeast wrote:
    But in the second example it tries to parse the whole string as a double?As far as Java is concerned, a string is just a bunch of characters. Java doesn't know that this particular string happens to be a mathematical expression that could be evaluated.
    If you want to evaluate a string as a mathematical expression you can do that out-of-the-box if you are using Java 6, through the new ScriptEngine functionality. Java 6 ships with a script engine that can evaluate JavaScript, so in this case you could do:
    import javax.script.*;
    public class EvalExample {
        public static void main(String[] args) {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
            try {
              Double result = (Double) jsEngine.eval("1 + 2 * 3");
              System.out.println(result);
            } catch (ScriptException ex) {
              ex.printStackTrace();
    }(Note that the cast to Double will fail if the expression you evaluate does not result in a number.)
    Edited by: Torgil on Feb 25, 2010 8:12 PM: Figured I should make the example an SSCCE :)

  • Converting double to String

    I am looking for a way to convert double to String.
    I think that I have to use wrapper like Double class and use toString(double d), but I am not sure how to do it.
    Since toString() is static method, I do not have to have an instance of the Double class, so I was wondering what's the correct way to do it.
    I need something like this:
    String MyString = new String (String1.concat ( My_doubleNumber.Double.toString() ) );
    Any Suggestions?
    Thanks!!!

    WOW thanks a lot. These are definately better than what I thought of doing originally.
    In case I need to use the wrapper class somewhere else, I am just wondering what would be a proper use of Double and String?

  • Converting Double to String without exponent

    Hi all,
    I am reading some values from Excelsheet using apache POI library. I have large numbers that need to stored into database as string and not numbers. hence, while reading the excelsheet values, i convert these number.. and the are received as double. While converting double into string I noticed that some values are represented in exponential form.. I would like to avoid this and have pure number values in the form of string,,..
    Can anybody tell me how to do it?
    Thanks in advance,
    Abdel Olakara

    java.text.DecimalFormat

  • Rounding double for string purposes

    Hello Forum,
    I have small problem:
    Let say I need to convert meters to feet. I have jTextFieldMeter for inputing the meters and jButtonCalculateFeet to calculate to feet. I also have jTextArea where resultS ARE displayed.
    Now, calculation is perfect (button action):
    double feet = Double.parseDouble(jTextFieldMeter) * 3.28083;
    Here is the problem: How do I display each result in jTextArea in new line and in this order;
    (jTextFieldMeter.getText() + " meters is " + feet(???) + " feet.") - but feet should be rounded after first decimal number so I get in jTextArea :
    "1 meters is 3.3 feet"
    And another question, how do I write in next line in jTextArea, so there are more lines (multiline).
    Now I get just one same line for each new result (deletes (or overvrites?) old result)
    Since I am a beginner I believe I might complicated simple task. If I am not understandable I will gladly explain more!
    Thanks and sorry for my English
    Kind regards, Beezgetz

    Hello Prigas,
    Thanxs for your reply. It helped me graet deal!
    JTextArea.append("Your text with new line\n"); works a charm!
    As for decimal places...
    I got it just fine, but that link of yours gave me another thing to worry.
    Is there a universal decimal separator? I mean . (point) or , (comma)?
    If I save my doubles into xml in my room in Slovenia and send those saved doubles to some dude in Finland, how does his computer interprets decimal separator?
    Am I makimg sense?
    Kind regards, Beezgetz

  • Printing out double quote string

    Hello,
    I would like to know how can i print out the double quote string (")
    in JSP using out.print(), because a double qoute has already used
    for indicating the string. If the string that i want to print out is including double quote("), how can i print that string out.
    THX !

    out.println("\"mystring\"");
    generally: backslash "\" is used in Java to quote special characters e.g. out.println("c:\\my documents\\bla");

  • Problem on Double.parseDouble

    Double.parseDouble(InputString); was error on my NetBeans 6.8 how to fixed it? I've tried to reinstall but still the same

    Make sure you are using CLDC 1.1. Double is not included in CLDC 1.0.
    Erik Wetterberg

  • Maybe you are looking for

    • Start clusterware (CRS) without starting instance in a node

      version ==> 11.2.0.1 os : Solaris 5.10 Using #$GRID_HOME/bin/crsctl start crsI can start CRS in a node. But , i don't want to start the instance in this node. I just want to start the clusterware and ASM instance in this node. Any idea how i can do t

    • How to store xml files in oracle as xmltype

      public class writexmldb2      public static void main(String args[]) throws SQLException, FileNotFoundException           DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());           Connection conn = DriverManager.getConnection("jd

    • Boot problem after 10.4.5 update

      I installed the 10.4.5 update on my new iMac Core Duo, rebooted when it asked me to. Upon reboot now I just get the boot screen followed by a blue screen with a cursor and it just stays there. I read you can fix this by going into Safe Mode. Anyone k

    • Approval Setup for SIT

      Hi, I want to setup AME for SIT in employee self service. Can any one let me know the step by step process. Regards, Vamsee Krishna

    • HT4972 what if i cannot update  my device to ios 5 due to connection error?

      what if i cannot update  my device to ios 5 due to connection error?