Discussions

Web tier: servlets, JSP, Web frameworks: How to format large Float to jsp?

  1. How to format large Float to jsp? (3 messages)

    Hi friends:

               I want to display a large number to jsp reading from database(Oracle).The number is "1111111111". The number in database is "1111111111" excactly and it is Float (126) . But after it displayed to jsp,it become "1111111112" ?! why JVM auto format Float number? The number "1111111112" is not what I want to see. I use NumberFormat class to format it,but no luck ;-(

     My code is:
    [code]
    public static String formatBigDecimal(Float f){ if(null!=f){
    NumberFormat nf=NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    int a=f.intValue();
    String result=nf.format(a);
    return result;
    }else{
    log.info("It is null null format");
    return null;
    }


    [/code]

    If I input number 300000000,it will display 3E. no! Why it couldn't display correctly? How to format large number for display correctly? Thks!!

    Threaded Messages (3)

  2. How to format large Float to jsp?[ Go to top ]

    Hi friends:           I want to display a large number to jsp reading from database(Oracle).The number is "1111111111". The number in database is "1111111111" excactly and it is Float (126) . But after it displayed to jsp,it become "1111111112" ?! why JVM auto format Float number? The number "1111111112" is not what I want to see. I use NumberFormat class to format it,but no luck ;-( My code is:[code]public static String formatBigDecimal(Float f){ if(null!=f){ NumberFormat nf=NumberFormat.getInstance(); nf.setGroupingUsed(false); int a=f.intValue(); String result=nf.format(a); return result; }else{ log.info("It is null null format"); return null; } [/code]If I input number 300000000,it will display 3E. no! Why it couldn't display correctly? How to format large number for display correctly? Thks!!

    This has to do with how float and doubles are represented in IEEE 754 notation.
    111111111 = 1.65568457543849945068359375 * 2^26

    127 is added as bias to 26 and stored in 8 bits and called exponent

    0.65568457543849945068359375 is stored in 23 bits
    If this fraction doesn't equal exactly to a series of 2 (with in 23 bits); some part gets truncated.
    When the floating value is read you will effectively get the truncated float value.


    Why don't you read the number as a String from the database.
  3. How to format large Float to jsp?[ Go to top ]

    Try using BigDecimal Data Type and pass the value as "String" to the BigDecimal Constructor. BigDecimal has a overloaded constructor 1) with Double as Parameter 2) with String as Parameter. Trying option 1 will add extra precisions, but Option2 won't. Refer the Java API Doc
  4. :)[ Go to top ]

    Thank you all! When I convert Float to String ,it will lose precisions. :(

     Now I change all Float to Double type in my web system. It is really a hard work.

    Thks!