Scientific Notation in Java

Hi,
In the hopes of enforcing a precision of 1.0e-16 for all the doubles in my Java application, I am trying
to apply a DecimalFormat pattern so that my doubles can be printed in scientific notation if necessary. I am doing:
DecimalFormat decf = (DecimalFormat)DecimalFormat.getInstance();
decf.applyPattern("0.################E0");
as the first step in the execution process but this is not working. Am I missing something?
Thanks,
Corrine

It might help if you explained what "not working" means in this case. You can only use formatting to control how the numbers appear to you, not how they are represented internally for calculation, if that's part of your question.

Similar Messages

  • Scientific notation and Java

    Hi. I Have the following questions. Would appreciate any response.
    I am using JDK 1.4.2
    Reading an Excel file with POI from appache.
    The spread sheet has mixed data, and text - no formulas, taht's taken care of
    Because of the nature of the application environment, we don't know the datatype in a cell ahead of time, so If I spot a number I get a nueric type, if I spot a character stream - I get a string, etc. ... but at the end of the cycle, in the application domain I have everything as STRINGS.
    Problem 1:
    In Excel file I have a entry: A = 20385759367
    In Java it comes as: A = 2.0385759367E10
    Problem 2:
    In Excel file I have a entry: A = 10
    In Java it comes as: A=10.0
    Is there some way, to get it reformated back to 20385759367, and to 10 without going through all kind of string patterning with substrings and recognizing "E" ect .... maybe there is a method in some class, that I don't know about ?

    double a = 20385759367.0;
    double b = 10.0;
    double c = 0.34567;
    java.text.NumberFormat f = new java.text.DecimalFormat("0.##");
    System.out.println(a+" -> "+f.format(a));
    System.out.println(b+" -> "+f.format(b));
    System.out.println(c+" -> "+f.format(c));

  • Converting from a double to scientific notation

    does anyone know how I can convert a double value to scientific notation?

    java.text.DecimalFormat can do that.

  • WKT Contains Scientific Notation

    I have a table with an SDO geometry column. Our data is stored in Web Mercator to simplify displaying maps on a web page. My team's preferred way of shuffling geometries around is via its WKT since this is human readable and widely used. So we are fetching the WKT directly from the database using the GET_WKT() method (right term?) on the SDO geoemtry.
    The problem is that when coordinates exceed 10 million in magnitude, those coordinates are represented in E notation (see http://en.wikipedia.org/wiki/Scientific_notation#E_notation). I need to convert this WKT to a .NET object for use with a particular library, and while it supports conversion from WKT, it blows up on the E notation. I'd call it a bug with the library except for the fact that Oracle itself can't parse WKTs with E notation, either. SDO_UTIL.VALIDATE_WKTGEOMETRY returns FALSE for the WKT that GET_WKT() generated, and SDO_UTIL.FROM_WKTGEOMETRY throws an error. I've also tested that SDO_UTIL.SDO_UTIL.TO_WKTGEOMETRY returns the same WKT.
    A large amount of code already depends on the geometry being in WKT format, which means that switching to another format would not be an easy change. For the moment, I'm parsing the WKT using SQL Server's geometry type (see http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.types.sqlgeometry_methods.aspx), and then converting it back to a WKT without E notation using its STAsText() method.
    Is there a way to force Oracle to not return E notation coordinates?
    This is occurring in both of the following versions of Oracle:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    PL/SQL Release 11.1.0.6.0 - Production
    "CORE     11.1.0.6.0     Production"
    TNS for 32-bit Windows: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production
    Sample SQL:
    The SRID in the following queries does not seem to exist out of the box in version 10 or Oracle. I ran these queries through Oracle SQL Developer.
    Query:
    SELECT MDSYS.SDO_GEOMETRY(2003,3785,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(-13426771.266146,5334024.8870015,-13425624.710722,5326534.0582305,-13412553.978887,5325922.5620044,-13412936.164029,5333719.1388884,-13426771.266146,5334024.8870015)).GET_WKT() FROM DUAL;
    Result:
    POLYGON ((-1.3426771266146E7 5334024.8870015, -1.3425624710722E7 5326534.0582305, -1.3412553978887E7 5325922.5620044, -1.3412936164029E7 5333719.1388884, -1.3426771266146E7 5334024.8870015))
    Query:
    SELECT SDO_UTIL.VALIDATE_WKTGEOMETRY(MDSYS.SDO_GEOMETRY(2003,3857,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(-13426771.266146,5334024.8870015,-13425624.710722,5326534.0582305,-13412553.978887,5325922.5620044,-13412936.164029,5333719.1388884,-13426771.266146,5334024.8870015)).GET_WKT()) FROM DUAL;
    Result:
    FALSE
    Query:
    SELECT SDO_UTIL.FROM_WKTGEOMETRY(MDSYS.SDO_GEOMETRY(2003,3785,NULL,MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1),MDSYS.SDO_ORDINATE_ARRAY(-13426771.266146,5334024.8870015,-13425624.710722,5326534.0582305,-13412553.978887,5325922.5620044,-13412936.164029,5333719.1388884,-13426771.266146,5334024.8870015)).GET_WKT()) FROM DUAL;
    Result:
    ORA-29532: Java call terminated by uncaught Java exception: java.lang.RuntimeException
    ORA-06512: at "MDSYS.SDO_UTIL", line 172
    29532. 00000 - "Java call terminated by uncaught Java exception: %s"
    *Cause:    A Java exception or error was signaled and could not be
    resolved by the Java code.
    *Action:   Modify Java code, if this behavior is not intended.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hello jpmc26,
    I am going to guess that most of us live our lives between the 180s and have not really noticed this before. I would call it a bug that needs an SR opened but is the bug on the coming or the going? If you look in the Simple Features 1.2.1 specification on pages 52 and 53 they clearly say that an "approximate numeric literal" of mantissa + E + exponent is valid. However, Oracle Spatial does not support the 1.2.1 spec. Rather they support something akin to the 1.1.0 specification. On pages 28 and 29 of that version there is no mention of approximate numeric literals as it first shows up in the 1.2.0 specification.
    So I would say either:
    1) Oracle Spatial supporting only the 1.1.0 specification and not much interested in updating to current specifications, should remove the output of scientific notation from the SDO_UTIL.to_WKTGEOMETRY procedure (match 1.1.0 spec).
    -or-
    2) Oracle Spatial looking forward to future compatibility with new OGC standards, should add support for parsing scientific notation to the SDO_UTIL.from_WKTGEOMETRY procedure (prepare for 1.2.1 spec).
    I guess its a policy decision on their side. Please update the posting as to what they say as I am curious about the topic.
    Many folks have largely abandoned these java-based, outdated, OGC converters. Feel free to search the forum for complaints, myself being one of the complainers. When you said "a large amount of code already depends" on WKT, my first thought was that must be really slow. Writing your own SDO to WKT converter in PLSQL is really easy and I believe that's what most of us have done. The other direction is more challenging but doable - I need to rewrite mine but its works well enough for straightforward stuff.
    Cheers,
    Paul

  • Double and scientific notation

    Hi,
    I am using a Double to store data but when i output it the value
    is printed in scientific notation example, 2.3333E5..I want to print it as decimal without the 'E' notation, is there a way to format it or set the precision in Java???
    Many Thanks

    You can have a look at NumberFormat and also search this forum because it's a frequently asked question.

  • Scientific Notation to Integer?

    I have a string like 1.780657E7 that I need to convert to an integer. I think that might be too big for Integer, so maybe BigInt would be better.
    Anyway, I can't figure out how to do this! I guess I could write my own method, but I'm sure it's already out there somewhere. I'm pretty new to Java.
    Thanks a lot,
    - Andrew.

    A small exegesis of prometheuzz's perfectly accurate, if slightly terse solution.
    Scientific notation is assumed to be floating-point. You must therefore parse a scientific-notation string using Float.parseFloat() or Double.parseDouble() and "integerise" the result if an integer is what you want.
    The last line is to show that your sample number is easy to fit in an int variable.

  • 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

  • How to prevent display in scientific notation

    I want to convert a large double value to a string,
    but when the value is greater than 10000000 , it will display in
    scientific notation , such as 3.435E8
    However, how can I convert it automatically to 343500000 because
    there is an interface program which do not accept the scientific
    notation format
    Thanks in advanced

    Start here: http://java.sun.com/j2se/1.4/docs/api/java/text/NumberFormat.html

  • 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

  • DecimalFormat scientific notation if necessary

    I would like to find a way to output a double value in a way that uses scientific notation only if the number of digits output would be at least 15. For instance, the value 12345000000000000 should be output as 1.2345E16, but 12345000 would not be output in scientific notation (and the same logic if the value is < 0). Is this possible with the DecimalFormat class?
    I tried using String.format("%.15g", value), but that always displays trailing 0s to fill the significant digits (e.g. 12.345 outputs "12.3450000000000"). I don't want it to output the trailing 0s.

    I would like to find a way to output a double value
    in a way that uses scientific notation only if the
    number of digits output would be at least 15. For
    instance, the value 12345000000000000 should be
    output as 1.2345E16, but 12345000 would not be output
    in scientific notation (and the same logic if the
    value is < 0). Is this possible with the
    DecimalFormat class?
    I tried using String.format("%.15g", value), but that
    always displays trailing 0s to fill the significant
    digits (e.g. 12.345 outputs "12.3450000000000"). I
    don't want it to output the trailing 0s.With DecimalFormat ( http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html )
    you can format the number in scientific notation but to control which numbers are formatted I think you must write some sort of if else

  • Numberformatter and scientific notation

    Hello all.  I'm having an issue with Numberformatter that I could use some assistance with.  It looks like this:
        <mx:NumberFormatter id="numberFormatter"
            precision="6"
            rounding="up"
            useThousandsSeparator="false"
            useNegativeSign="true"/>
    I'm applying it to a Number object that was created from a deserialized java BigDecimal.  In most cases, this is successful. So, 0.000024603877571 becomes 0.000025 and so on.
    However, in some cases, my Number is in scientific notation like "0E-15".  In this case, the NumberFormatter formats the number as -15.000000.  Not helpful.  Any ideas on what is going on and how I might could work around it?

    Thanks for the quick response, Michael.  I was about to simply change the sending of the numbers as a string when I decided to try one more thing.  If I use toFixed() on my number first (before the NumberFormatter.format() function) it seems to fix the issue.  So, for example, in my label function for a column of a datagrid that has Numbers that sometimes appear in scientific notation, I do something like this:
                public function myNumberLabelFunction(item:Object, column:DataGridColumn):String
                    var myNumber:Number = item.number;
                    var myNumberString:String = myNumber.toFixed(20);
                    return numberFormatter.format(myNumberString);
    That (toFixed) appears to not mess up the regular numbers as well as the ones that have E notation.  I don't know if anyone has any thoughts on the workaround.  It seems to work find since my formatter is ultimately rounding to a precison of 6.

  • DecimalFormat issues/Scientific notation

    I have 2 issues with formatting numbers with scientific notation via the DecimalFormat class
    ISSUE 1: Disregard of the number of MAXIMUM FRACTOINAL DIGITS
         in the code:
                                     NumberFormat nf = NumberFormat.getInstance();
                                    DecimalFormat df = (DecimalFormat)nf;
                                    df.applyPattern("#00.#E0");
                                    System.out.println( df.format(12345678)); 
                                       it printed: 12.35E6
         Why does it violate my request for one significant digit beyond the decimal
         point?. (Note, this problem
    only seems to occur when when the sum of MAX integer and Max fractional
    digits in my pattern is 4)
    ISSUE 2:
    Number of significant digits displayed:- I really just need a sanity check on this one
    The 1.4.2 API for DecimalFormat states
    ?     The number of significant digits in the mantissa is the sum of the minimum integer and
    maximum fraction digits, and is unaffected by the maximum integer digits. For example,
    12345 formatted with "##0.##E0" is "12.3E3". To show all digits, set the significant digits
    count to zero. The number of significant digits does not affect parsing.
    I tried this ? it displays 123.45E3, or 5 significant digits? Looks like the number of significant digits
    is MAX integer + MAX fractional digits in a pattern. Am I correct (and the API not correct)?
    thanks
    carol

    Thanks. I'm assuming you're responding to issue #1. I did try it, and it worked, as expected. I never seem to have an issue when all symbols
    preceding the decimal are 0. My issue, I suppose, is the inconsistency of how the formatting
    works, when it comes to the number of fractional digit positions. Most of the times it 'behaves' and
    only prints out the number of digits you ask, but sometimes it does not.
    I've tested quite a few combinations. I'm attaching the code (in case you need help sleeping tonight).
    The only 'pattern' I've noticed is that this issue only occurs when the total number of digits specified
    in the pattern (before and after decimal) is 4. (exception ... if all digits specified before the decimal
    are 0s, this never occurs)
    I know a simple solution ... make sure I never have
    a total of 4 #s and 0s in my pattern. But again, my question is why ... and/or ... does this type of
    inconsistency crop up elsewhere.
    import java.util.*;
    import java.text.*;
    public class x {
         public static void main(String [] args) {
              NumberFormat nf = NumberFormat.getInstance();
              DecimalFormat df = (DecimalFormat)nf;
              // these 3 work like I'd expect: 3 digits to the left, one to the right w/ rounding
              // signif digits = max int digits + max fractional digits
              df.applyPattern("000.#E0");
              System.out.println( df.format(12345678)); // 123.5E5
              df.applyPattern("00.#E0");
              System.out.println( df.format(12345678)); // 12.3E6
              df.applyPattern("0.#E0");
              System.out.println( df.format(12345678)); // 1.2E7
              // signif digits = TOTAL int digits + max fractional digits
         System.out.println("X");
              df.applyPattern("###.#E0");                    // how did it decide to place decimal where it did?
              System.out.println( df.format(12345678)); // 12.35E6    // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              df.applyPattern("##.#E0");
              System.out.println( df.format(12345678)); // 12.3E6
              df.applyPattern("#.#E0");
              System.out.println( df.format(12345678)); // 1.2E7
              //signif digits - TOTAL int digits + max fractional didgits
         System.out.println("");
         System.out.println("XXXXXXXX");
              df.applyPattern("#000.#E0");
              System.out.println( df.format(12345678));  // 1234.6E4
              df.applyPattern("#00.#E0");
              System.out.println( df.format(12345678));  // 12.35E6       // how did it decide to place decimal where it did?
                                                 // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              df.applyPattern("#0.#E0");
              System.out.println( df.format(12345678)); //  12.3E6
              // significant digtis = TOTAL int digits + max fractional digits
         System.out.println("");
              df.applyPattern("###0.#E0");
              System.out.println( df.format(12345678));  // 1234.6E4
              df.applyPattern("##0.#E0");                    // how did it decide to place decimal where it did?
              System.out.println( df.format(12345678));  // 12.35E6     // why did it violate my "1 max fractional digit"
                                                 // request? I would have expected 123.5E5
              System.out.println( df.format(12345678));  // 12.35E6
              df.applyPattern("##.#E0");
              System.out.println( df.format(12345678));  // 12.3E6
    //API example from DecimaFormat RE Scientific Notation.. api says this will print 12.3E3
              df.applyPattern("###.##E0");
              System.out.println( df.format(12345)); //12.345E3   //violates max fractiona digit request
    //NOTE DOCS ARE WRONG ... the number of significant digits is = to max integer digits (number of # and 0 prior
    // to decimal point)  PLUS max number of digits after the decimal point... NOT Min. Integer digits + Max fractional digits
              // suggested pattern
              df.applyPattern("000000.##E0");
              System.out.println( df.format(12345678));  //123456.78

  • Display Large Float w/o Scientific Notation

    I have a series of dollar amounts (from an SQL cursor) that I am summing up using a java.lang.Float. The values total correctly, but when I display the value it is displayed using Scientific Notation (4.19150150185925 E12). I need to write my total value to a file that will be exported to another application (mainframe). Therefore, the value when written to the output file must be 4191501501859.25. How do I get the value in that form, instead of the scientific notation form?
    Should I be using a different type to sum my values into? The max value my total can reach is 99999999999999999.999
    Thanks.

    No, I meant precisely what I said. If BigDecimal
    does indeed have a valueOf method that accepts a
    string, please notify Sun, as they will certainly
    have to update the documentation -- didn't YOU
    read the documentation link that you yourself
    sent me?
    No, of course not, I only checked that it indeed does not have any method that takes a String parameter and that the method to "add" numbers is really called "add".
    By the way, a constructor that takes a String parameter does pretty much the same thing as a method that takes a String parameter and returns a new instance of the class. There is no significant difference between Float's valueOf(String) and the Float(String) constructor as far the user of the API is concerned.
    (Looking up the source just for fun I see that Float.valueOf(String) and Float(String) do completely different things, and Float(String) creates a temporary extra Float object. The comment above says: "REMIND: this is inefficient". Interesting.)
    Probably not, you were apparently too busy taking
    a 'tude.No doubt! :-)

  • Decimal Format and Scientific Notation

    I am trying to print numbers in scientific notation using the Decimal Format class. What follows is a simple test program I wrote to find the bug. So far, I have not found a solution.
    import java.text.*;
    public class formatted {
    public static void main (String Arguments[]) {
    DecimalFormat form = new DecimalFormat("0.###E0");
         double numb = 123456.789;
         System.out.println("Nuber is: " +
    form.format(numb));
    The output of this program is... Nuber is: 123456E
    The output is the same if numb is an int, float, or double. If I format the number as "#####.0" or "#####.00" the output is correct. I think that I am following the rules for formatting a number in scientific notation as the process is outlined in the documentation (provided below).
    ***** From Decimal Format under Scientific Notation ***
    Numbers in scientific notation are expressed as the product of a mantissa and a power of ten, for
    example, 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 <= x < 10.0,
    but it need not be. DecimalFormat can be instructed to format and parse scientific notation only via a
    pattern; there is currently no factory method that creates a scientific notation format. In a pattern,
    the exponent character immediately followed by one or more digit characters indicates scientific
    notation. Example: "0.###E0" formats the number 1234 as "1.234E3".
    Anyone understand how the short program is incorrectly written?
    Marc

    The problem is
    format = "0.###E0"
    input number = 123456.789
    output = 123456E (not scientific notation!)
    This is not scientific notation at all. There is no decimal point given and no value in the exponent.
    I understand entirely that by adding more #'es will provide more precision. The bug I have is the output is not printed in the scientific format; other formats work.
    MArc

  • Int printing out as scientific notation

    maybe doing something stupid here but I can't seem to pick it up.
    I have a Window that calls a subclass to display a calculator, and then returns the final value to the Window, if I input 10 digits it prints on as a 12345678E5
    something like that.
    Anywho here's the two methods that deal with value in the subclass( calculator )
    public int ReturnNumber(){//the method that will return the value from the keyboard
       int final_number = Integer.parseInt(number); 
        return final_number;   // returns value to question screen
      private void NextButtonActionPerformed (java.awt.event.ActionEvent evt) {
       if ( value.length() != allowable_answers[currentQuestionNumber] ){
                     JOptionPane.showMessageDialog(this, "Please make a valid entry.", "Invalid",
                     JOptionPane.WARNING_MESSAGE );
                     value.replace(0,counter,""); 
                     jTextField1.setText( null );
                     return;
        else {
                number = value.toString();
               setVisible(false);
               frame.final_number = ReturnNumber();
               frame.userMakeSelection = true;
               frame.FinalTimer.start();
               frame.ButtonSelected();Code from window that deals with the number
    if(Numeric[currentQuestionNumber]){
                currentAnswers[currentQuestionNumber][1] = final_number;// currentAnswers is a float[][]
                numeric_question_value[currentQuestionNumber][0] = final_number;// used in poll frequency
              }// numeric is a int[]
            else
                currentAnswers[currentQuestionNumber][currentChoice] = currentChoice;Is from trying to jam an int into float?
    Any suggestions
    Jim

    Is from trying to jam an int into float?That's exactly the cause. Here are some solutions:
    - Use java.text.DecimalFormat to format the output or cast the float to an integer type when you want to print it (presicion might become a problem).
    - Keep the number in an int or long all the time. This way you'll not lose any presicion.
    Explanation can be found in the API docs of Float.toString():"If the argument is NaN, the result is the string "NaN".
    Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('-'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
    If m is less than 10^-3 or not less than 10^7, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10n<=m<1; then let a be the mathematically exact quotient of m and 10n so that 1<a<10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (.), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (E), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int) of one argument."

  • Maybe you are looking for