Float.parseFloat("173879.04")

Why it returns 173879.05 ? IS THIS a bug in Java ?

Yes, agree, I have done something similar for adding double, and java
'kill' me.
BigDecimal is a good way, if and only if you pass 'string' to constructor, else it still add wrong double...
So read input as string instead and catch some exceptions...
I have an example of it when doing GUI.
I also, use some method to try fix but lead to losing precision, such as
double b;
double c;
int a = int (b * 100);
c = a / 100;
Or if you need to use GUI, then java.text.* will help...

Similar Messages

  • Null pointer Exception with Float.parseFloat

    I need to assign a float value from a database to a variable recurrently throughout a while loop. but i am getting a null pointer exception error:
    while ( rs.next() )
         out.println("<TR>");
              float corr = Float.parseFloat((String) request.getParameter("echo"));
              out.println("<center><TD><b><font color = #990000>" + rs.getString("race_number") + "</b></TD>");
              out.println("<center><TD><b><font color = #990000>" + rs.getString("sail_number") + "</b></TD>");
              out.println("<center><TD><b><font color = #990000>" + rs.getString("finish_time_elapsed") + "</b></TD>");
              out.println("<center><TD><b><font color = #990000>" + rs.getString("echo") + "</b></TD>");
              out.println("</TR>");
    I've also tried:
    float corr = Float.parseFloat( String request.getParameter("echo"));
    float corr = 0;
    corr Float.parseFloat((String) request.getParameter("echo"));
    corr = echo;
    corr = request.getParameter("echo");
    corr = rs.getString("echo");
    corr = Float.parseFloat(request.getParameter("echo"));
    temp = rs.getFloat("Problem_Description");
    Any ideas Please!!!

    Null pointer exception means that the value you are trying to turn into a Float is null. Probably request.getParameter("echo") returns null.
    Is "echo" a request parameter, or a field you want to get from the database?
    request.getParameter() has nothing to do with a database query.
    That is your http request coming from the form submission. It won't change.
    If "echo" is meant to be a request parameter, then make sure the parameter is actually present.
    If its a database field (stored as a number) then
    float corr = rs.getFloat("echo");
    should do the trick.
    Can the value be null in the database?
    Cheers,
    evnafets

  • Error Converting "1,300" to Float using Float.parseFloat()

    I need to convert a string in the format xx,xxx.00 to a float value.
    But I get java.lang.NumberFormatException by using Float.parseFloat("xx,xxx.00")
    What can I do?

    Look at java.text.NumberFormat to parse numbers in a specific format.
    regards,
    Owen

  • Issue with Float.parseFloat

    Hi,
    I tried the following code. Float.parseFloat("23d")does not throw an exception. The below code prints output as 23.0.
    String s = new String ("23d");
    try{
    System.out.println(Float.parseFloat(s));
    catch(Exception e){
    System.out.println("not a number..");
    How can I make Float.parseFloat("23d") throw an exception? Please help.
    thanks.
    roshni.

    here the d determine that this is double variable.
    so this is not give any exception.
    if you use any other character then it throw the exception.

  • Regarding Float.parseFloat method

    Hi,
    i have two text boxes,one is Quantity another Price i want Qantity as integer and Price as float while giving input.
    if user giv other than those i need to display error for that i done for Integer.parseInt(getparameter(..)) for this if the string is not int,it raising exception but for Float.parseFloat(getparameter(..)) for this it is not raising any exception.i am not getting what is the reason for that
    Thanks in advance
    nagaraju

    if(this.price==null||this.price.equals(""))
    ActionError ae1=new ActionError("pricereq");
    aes.add("price",ae1);
    else{
    *try{*
    *System.out.println(this.price);*
    *Float.parseFloat(this.price);*
    *catch(Exception e)*
    *ActionError ae2=new ActionError("pricenotfloat");*
    *aes.add("price",ae2);*
    }I wrote that code in struts to validate the form, in that when i entered the integer value in price text field it must show price must be float. but exception not raising in that highleted part
    i w

  • Float.parseFloat

    I am compiling my code with jdk 1.3 and getting this error when I compile:
    Error: cannot resolve symbol: method parseFloat (java.lang.String) in class java.lang.Float
    My class path:
    .;C:\jdk13\lib\;C:\jdk13\lib\tools.jar;C:\jdk13\lib\dt.jar;C:\jdk13\jre\lib\rt.jar;C:\jdk13\jre\lib\i18n.jar
    And here is my method...
    public void setGrandTotal(String f){
    this.grandTotal=Float.parseFloat(f.trim());
    Can some one tell me why can not resolve parseFloat
    Thank you

    When I compile your method in isolation, it compiles fine. Have you checked for syntax errors above it in the code? Does the code compile clean if you comment out that method?
    Normally you do not need to specify the java libraries in your classpath. Have you tried compiling with "javac -classpath . file" ?

  • Java.lang.NoSuchMethodError: java.lang.Float: method parseFloat(Ljava/lang/

    java.lang.NoSuchMethodError: java.lang.Float: method parseFloat(Ljava/lang/String;)F not found
    WHAT WOULD MAKE THIS HAPPEN. THIS SEEMS TO WORK IN JDK1.3.1 BUT NOT IN BLACKDOWN 1.1.3_V3
    THIS IS MY CODE:
    try{
    DecimalFormat dfp = new DecimalFormat( "0.00" );
    if(!Price.equals("")) {
    float MyFloat = Float.parseFloat(Price);
    Price = dfp.format(MyFloat);
    }catch(NumberFormatException nfe){
    PriceValid = 1;

    This error says:
    - There is no method called "parseFloat" that receives a String as parameter in class java.lang.Float.
    Look the method "parseFloat" at the class java.lang.Float!!

  • Error:  java/lang/String  & parsefloat not a method in class Float (j0235)

    Hi,
    I don't know why i amgetting this error which says: 'unable to locate system class: java/lang/String.
    I have compiled and executed the reader method separately on a command prompt and it is working, but when i do it in microsoft visual j++, i am getting this run time error.
    I also have rt.jar in the classpath.
    If i don't have this rt.jar in my classpath, it is giving me a compilation error: parsefloat is not a method in class Float (j0235).
    somebody please help.
    Jagadish.
    // an agent is floating randomly.
    import java.util.*;
    import vrml.*;
    import vrml.node.*;
    import vrml.field.*;
    import java.io.*;
    public class FloatingAgent extends Script{
    SFVec3f setAgentPosition;
    SFRotation setAgentRosition;
    static int count=0;
    float agentPosition[] = new float[3];
    float agentRosition[] = new float[4];
    float rotangle = 0.0f;
    float aRad= (float) (Math.PI/180);
    public void initialize(){
    setAgentPosition =
    (SFVec3f)getEventOut("setAgentPosition");
    setAgentRosition =
    (SFRotation)getEventOut("setAgentRosition");
    // initialize the agent position.
    agentPosition[0] = 0.0f;
    agentPosition[1] = 0.0f;
    agentPosition[2] = 0.0f;
    agentRosition[0] = 0.0f;
    agentRosition[1] = 0.0f;
    agentRosition[2] = 1.0f;
    agentRosition[3] = 0.0f;
    public void processEvent(Event e){
    if(e.getName().equals("interval") == true){
    moveAgent();
    void moveAgent()
    agentPosition = reader();
    rotangle += 2.0f;
    agentRosition[3] = rotangle * aRad;
    // move the agent to the new position.
    setAgentPosition.setValue(agentPosition);
    setAgentRosition.setValue(agentRosition);
    }//move agent
    static float[] reader()
    float p1[] = new float[3];
    try{
    FileReader fr = new FileReader("data.txt");
    BufferedReader br = new BufferedReader(fr);
    String s;
    int count1=0;
    count++;
    try{
    while((s=br.readLine())!=null)
    count1++;
    StringTokenizer st = new StringTokenizer(s);
    if(count1==count)
    int i=0;
    while(st.hasMoreTokens())
    p1[i++]=Float.parseFloat(st.nextToken());
    }//if
    }//end of stringTokenizer while.
    fr.close();
    catch(IOException f)
    System.out.println("file cannot be opened");
    }//try
    catch(FileNotFoundException e)
    System.out.println("file doesn't exist");
    } //try
    return p1;
    }//reader

    still using Visual J++ ???

  • Issue with setting float point in Textfield

    hi
    i have an issue with float input in a textfield.
    what i want to do is.
    when the user start typing numerics it should accept from right hand side and keep appending value from right hand side.
    for ex
    if i want to enter 123.45
    user starts entering
    1 then it should display as 0.01
    2 then it should display as 0.12
    3 then it should display as 1.23
    4 then it should display as 12.34
    5 then it should display as 123.45
    to achive this i have written the code as below
    public class Test{
         public static void main(String[] a){
         try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
    DecimalFormat format = new DecimalFormat();
    format.setGroupingUsed(true);
    format.setGroupingSize(3);
    format.setParseIntegerOnly(false);
    JFrame f = new JFrame("Numeric Text Field Example");
    final DecimalFormateGen tf = new DecimalFormateGen(10, format);
    // tf.setValue((double) 123456.789);
    tf.setHorizontalAlignment(SwingConstants.RIGHT);
    JLabel lbl = new JLabel("Type a number: ");
    f.getContentPane().add(tf, "East");
    f.getContentPane().add(lbl, "West");
    tf.addKeyListener(new KeyAdapter(){
         public void keyReleased(KeyEvent ke){
              char ch = ke.getKeyChar();
              char key;
              int finalres =0;
              String str,str1 = null,str2 =null,str3 = null,str4= null;
              if(ke.getKeyChar() == KeyEvent.VK_0 || ke.getKeyChar() == KeyEvent.VK_0 ||
                        ke.getKeyChar() == KeyEvent.VK_0 || ke.getKeyChar() == KeyEvent.VK_1 || ke.getKeyChar() == KeyEvent.VK_2 ||
                             ke.getKeyChar() == KeyEvent.VK_3 || ke.getKeyChar() == KeyEvent.VK_4 || ke.getKeyChar() == KeyEvent.VK_5 ||
                             ke.getKeyChar() == KeyEvent.VK_6 || ke.getKeyChar() == KeyEvent.VK_7 || ke.getKeyChar() == KeyEvent.VK_8 ||
                             ke.getKeyChar() == KeyEvent.VK_9 ){
                   double value1 = Double.parseDouble(tf.getText());
                   int position = tf.getCaretPosition();
                   if(tf.getText().length() == 1){
                        if(tf.getText() != null || tf.getText() != ""){
                        value1 = value1 / 100;
                        tf.setText(String.valueOf(value1));
                   /*else if(tf.getText().length() == 3){
                        str = tf.getText();
                        for(int i=0;i<str.length();i++){
                             if(str.charAt(i) == '.'){
                                  str1 = str.substring(0,i);
                                  str2 = str.substring(i+1,str.length()-1);
                                  break;
                        key = ke.getKeyChar();
                        finalres = calculate.calculate1(str2,key);
                        str3 = merge.merge1(str1,finalres);
                        tf.setText(str3);
                        System.out.println(key);
                        System.out.println(str1);
                        System.out.println(str2);
                   else{
                        value1 = Float.parseFloat(tf.getText());
                        value1 = value1*10;
                        tf.setText(String.valueOf(value1));
    tf.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    try {
    tf.normalize();
    Long l = tf.getLongValue();
    System.out.println("Value is (Long)" + l);
    } catch (ParseException e1) {
    try {
    Double d = tf.getDoubleValue();
    System.out.println("Value is (Double)" + d);
    } catch (ParseException e2) {
    System.out.println(e2);
    f.pack();
    f.setVisible(true);
    import javax.swing.JTextField;
    * Created on May 25, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author jagjeevanreddyg
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import java.text.ParseException;
    import java.text.ParsePosition;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.AbstractDocument.Content;
    public class DecimalFormateGen extends JTextField implements
    NumericPlainDocument.InsertErrorListener {
         public DecimalFormateGen() {
         this(null, 0, null);
         public DecimalFormateGen(String text, int columns, DecimalFormat format) {
         super(null, text, columns);
         NumericPlainDocument numericDoc = (NumericPlainDocument) getDocument();
         if (format != null) {
         numericDoc.setFormat(format);
         numericDoc.addInsertErrorListener(this);
         public DecimalFormateGen(int columns, DecimalFormat format) {
         this(null, columns, format);
         public DecimalFormateGen(String text) {
         this(text, 0, null);
         public DecimalFormateGen(String text, int columns) {
         this(text, columns, null);
         public void setFormat(DecimalFormat format) {
         ((NumericPlainDocument) getDocument()).setFormat(format);
         public DecimalFormat getFormat() {
         return ((NumericPlainDocument) getDocument()).getFormat();
         public void formatChanged() {
         // Notify change of format attributes.
         setFormat(getFormat());
         // Methods to get the field value
         public Long getLongValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getLongValue();
         public Double getDoubleValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getDoubleValue();
         public Number getNumberValue() throws ParseException {
         return ((NumericPlainDocument) getDocument()).getNumberValue();
         // Methods to install numeric values
         public void setValue(Number number) {
         setText(getFormat().format(number));
         public void setValue(long l) {
         setText(getFormat().format(l));
         public void setValue(double d) {
         setText(getFormat().format(d));
         public void normalize() throws ParseException {
         // format the value according to the format string
         setText(getFormat().format(getNumberValue()));
         // Override to handle insertion error
         public void insertFailed(NumericPlainDocument doc, int offset, String str,
         AttributeSet a) {
         // By default, just beep
         Toolkit.getDefaultToolkit().beep();
         // Method to create default model
         protected Document createDefaultModel() {
         return new NumericPlainDocument();
         // Test code
         public static void main(String[] args) {
         try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         } catch (Exception evt) {}
         DecimalFormat format = new DecimalFormat("#,###.###");
         format.setGroupingUsed(true);
         format.setGroupingSize(3);
         format.setParseIntegerOnly(false);
         JFrame f = new JFrame("Numeric Text Field Example");
         final DecimalFormateGen tf = new DecimalFormateGen(10, format);
         tf.setValue((double) 123456.789);
         JLabel lbl = new JLabel("Type a number: ");
         f.getContentPane().add(tf, "East");
         f.getContentPane().add(lbl, "West");
         tf.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
         try {
         tf.normalize();
         Long l = tf.getLongValue();
         System.out.println("Value is (Long)" + l);
         } catch (ParseException e1) {
         try {
         Double d = tf.getDoubleValue();
         System.out.println("Value is (Double)" + d);
         } catch (ParseException e2) {
         System.out.println(e2);
         f.pack();
         f.setVisible(true);
         class NumericPlainDocument extends PlainDocument {
         public NumericPlainDocument() {
         setFormat(null);
         public NumericPlainDocument(DecimalFormat format) {
         setFormat(format);
         public NumericPlainDocument(AbstractDocument.Content content,
         DecimalFormat format) {
         super(content);
         setFormat(format);
         try {
         format
         .parseObject(content.getString(0, content.length()), parsePos);
         } catch (Exception e) {
         throw new IllegalArgumentException(
         "Initial content not a valid number");
         if (parsePos.getIndex() != content.length() - 1) {
         throw new IllegalArgumentException(
         "Initial content not a valid number");
         public void setFormat(DecimalFormat fmt) {
         this.format = fmt != null ? fmt : (DecimalFormat) defaultFormat.clone();
         decimalSeparator = format.getDecimalFormatSymbols()
         .getDecimalSeparator();
         groupingSeparator = format.getDecimalFormatSymbols()
         .getGroupingSeparator();
         positivePrefix = format.getPositivePrefix();
         positivePrefixLen = positivePrefix.length();
         negativePrefix = format.getNegativePrefix();
         negativePrefixLen = negativePrefix.length();
         positiveSuffix = format.getPositiveSuffix();
         positiveSuffixLen = positiveSuffix.length();
         negativeSuffix = format.getNegativeSuffix();
         negativeSuffixLen = negativeSuffix.length();
         public DecimalFormat getFormat() {
         return format;
         public Number getNumberValue() throws ParseException {
         try {
         String content = getText(0, getLength());
         parsePos.setIndex(0);
         Number result = format.parse(content, parsePos);
         if (parsePos.getIndex() != getLength()) {
         throw new ParseException("Not a valid number: " + content, 0);
         return result;
         } catch (BadLocationException e) {
         throw new ParseException("Not a valid number", 0);
         public Long getLongValue() throws ParseException {
         Number result = getNumberValue();
         if ((result instanceof Long) == false) {
         throw new ParseException("Not a valid long", 0);
         return (Long) result;
         public Double getDoubleValue() throws ParseException {
         Number result = getNumberValue();
         if ((result instanceof Long) == false
         && (result instanceof Double) == false) {
         throw new ParseException("Not a valid double", 0);
         if (result instanceof Long) {
         result = new Double(result.doubleValue());
         return (Double) result;
         public void insertString(int offset, String str, AttributeSet a)
         throws BadLocationException {
         if (str == null || str.length() == 0) {
         return;
         Content content = getContent();
         int length = content.length();
         int originalLength = length;
         parsePos.setIndex(0);
         // Create the result of inserting the new data,
         // but ignore the trailing newline
         String targetString = content.getString(0, offset) + str
         + content.getString(offset, length - offset - 1);
         // Parse the input string and check for errors
         do {
         boolean gotPositive = targetString.startsWith(positivePrefix);
         boolean gotNegative = targetString.startsWith(negativePrefix);
         length = targetString.length();
         // If we have a valid prefix, the parse fails if the
         // suffix is not present and the error is reported
         // at index 0. So, we need to add the appropriate
         // suffix if it is not present at this point.
         if (gotPositive == true || gotNegative == true) {
         String suffix;
         int suffixLength;
         int prefixLength;
         if (gotPositive == true && gotNegative == true) {
         // This happens if one is the leading part of
         // the other - e.g. if one is "(" and the other "(("
         if (positivePrefixLen > negativePrefixLen) {
         gotNegative = false;
         } else {
         gotPositive = false;
         if (gotPositive == true) {
         suffix = positiveSuffix;
         suffixLength = positiveSuffixLen;
         prefixLength = positivePrefixLen;
         } else {
         // Must have the negative prefix
         suffix = negativeSuffix;
         suffixLength = negativeSuffixLen;
         prefixLength = negativePrefixLen;
         // If the string consists of the prefix alone,
         // do nothing, or the result won't parse.
         if (length == prefixLength) {
         break;
         // We can't just add the suffix, because part of it
         // may already be there. For example, suppose the
         // negative prefix is "(" and the negative suffix is
         // "$)". If the user has typed "(345$", then it is not
         // correct to add "$)". Instead, only the missing part
         // should be added, in this case ")".
         if (targetString.endsWith(suffix) == false) {
         int i;
         for (i = suffixLength - 1; i > 0; i--) {
         if (targetString
         .regionMatches(length - i, suffix, 0, i)) {
         targetString += suffix.substring(i);
         break;
         if (i == 0) {
         // None of the suffix was present
         targetString += suffix;
         length = targetString.length();
         format.parse(targetString, parsePos);
         int endIndex = parsePos.getIndex();
         if (endIndex == length) {
         break; // Number is acceptable
         // Parse ended early
         // Since incomplete numbers don't always parse, try
         // to work out what went wrong.
         // First check for an incomplete positive prefix
         if (positivePrefixLen > 0 && endIndex < positivePrefixLen
         && length <= positivePrefixLen
         && targetString.regionMatches(0, positivePrefix, 0, length)) {
         break; // Accept for now
         // Next check for an incomplete negative prefix
         if (negativePrefixLen > 0 && endIndex < negativePrefixLen
         && length <= negativePrefixLen
         && targetString.regionMatches(0, negativePrefix, 0, length)) {
         break; // Accept for now
         // Allow a number that ends with the group
         // or decimal separator, if these are in use
         char lastChar = targetString.charAt(originalLength - 1);
         int decimalIndex = targetString.indexOf(decimalSeparator);
         if (format.isGroupingUsed() && lastChar == groupingSeparator
         && decimalIndex == -1) {
         // Allow a "," but only in integer part
         break;
         if (format.isParseIntegerOnly() == false
         && lastChar == decimalSeparator
         && decimalIndex == originalLength - 1) {
         // Allow a ".", but only one
         break;
         // No more corrections to make: must be an error
         if (errorListener != null) {
         errorListener.insertFailed(this, offset, str, a);
         return;
         } while (true == false);
         // Finally, add to the model
         super.insertString(offset, str, a);
         public void addInsertErrorListener(InsertErrorListener l) {
         if (errorListener == null) {
         errorListener = l;
         return;
         throw new IllegalArgumentException(
         "InsertErrorListener already registered");
         public void removeInsertErrorListener(InsertErrorListener l) {
         if (errorListener == l) {
         errorListener = null;
         public interface InsertErrorListener {
         public abstract void insertFailed(NumericPlainDocument doc, int offset,
         String str, AttributeSet a);
         protected InsertErrorListener errorListener;
         protected DecimalFormat format;
         protected char decimalSeparator;
         protected char groupingSeparator;
         protected String positivePrefix;
         protected String negativePrefix;
         protected int positivePrefixLen;
         protected int negativePrefixLen;
         protected String positiveSuffix;
         protected String negativeSuffix;
         protected int positiveSuffixLen;
         protected int negativeSuffixLen;
         protected ParsePosition parsePos = new ParsePosition(0);
         protected static DecimalFormat defaultFormat = new DecimalFormat();
    this is not working as desired pls help me.
    can we use this code and get the desired result or is there any other way to do this.
    it is very urgent for me pls help immediately
    thanks in advance

    Hi camickr
    i learned how to format the code now, and u also responded for my testarea problem , iam very much thankful to u, and now i repeat the same problem what i have with a text field.
    actually i have window with a textfield on it and while end user starts entering data in it , it should be have as follows
    when the user start typing numerics it should accept from right hand side and keep appending value from right hand side.
    first the default value should be as 0.00 and as the user starts entering
    then it is as follows
    for ex
    if i want to enter 123.45
    user starts entering
    1 then it should display as 0.01
    2 then it should display as 0.12
    3 then it should display as 1.23
    4 then it should display as 12.34
    5 then it should display as 123.45
    i hope u will give me quick reply because this is very hard time for me.

  • Float type problem helppppppppp

    I have a jsp page, which retrieves values from a html page, my problem is that
    i can insert the values in database, but the problem is that it does not insert the flot type values...
    like 21.21, 242.52. It shows only 21,242
    it does not shows in float type.
    html form:
    <input type="text" name="code" size="5" maxlength="5">
    <input type="text" name="Description" size="65">
    <input type="text" name="DrAmount" size="12" >
    <input type="text" name="CrAmount" size="12" >
    <SELECT name="type">
    <option value="" selected></option>
    <option VALUE="C">C</option>
    <option VALUE="O">O</option>
    <option VALUE="OI">OI</option>
    <option VALUE="OR">OR</option>
    <option VALUE="S">S</option>
    <option VALUE="SB">SB</option>
    <option VALUE="SG">SG</option></select>
    <input name="pct" type="text" size="6" maxlength="5" >
    jsp page:
    <html>
    <head>
    <%@ page
         import = "java.io.*"
         import = "java.lang.*"
         import = "java.sql.*"
    %>
    <title></title>
    </head>
    <body>
    <h1></h1>
    <%
         String Code,Description,Dr_Amount,Cr_Amount,Pct,Type, sql1 ;
         ResultSet results;
         PreparedStatement sql;
         try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection conn=DriverManager.getConnection("jdbc:odbc:pf","scott","ttlscott");
              try
                   int gl_code;
                   Float db_amt,cr_amt,gl_pct;
                   String gl_descr, gl_type;
                   boolean     doneheading = false;
    Statement s=conn.createStatement();
    Code = request.getParameter("code");
    Description = request.getParameter("Description");
    Dr_Amount=request.getParameter("DrAmount");               
    Cr_Amount=request.getParameter("CrAmount");
    Type = request.getParameter("type");
    Pct=request.getParameter("pct");
    PreparedStatement pstmt = conn.prepareStatement(
    ("INSERT INTO gl_mast VALUES (?, ?, ?, ?, ?,?)"));
    pstmt.setInt(1,Integer.parseInt(request.getParameter("Code")));
    pstmt.setString(2, request.getParameter("Description"));
    pstmt.setFloat(3,Float.parseFloat(request.getParameter("Dr_Amount")));
    pstmt.setFloat(4,Float.parseFloat(request.getParameter("Cr_Amount")));
    pstmt.setString(5, request.getParameter("Type"));
    pstmt.setFloat(6,Float.parseFloat(request.getParameter("Pct")));
    pstmt.executeUpdate();
                   sql = conn.prepareStatement("SELECT * FROM gl_mast WHERE gl_code = '" + Code + "'");
                   results = sql.executeQuery();
                   while(results.next())
                        if(! doneheading)
                             out.println("<table border=2>");
                             doneheading = true;
    gl_code = results.getInt("gl_code");
    gl_descr = results.getString("gl_descr");
    db_amt = results.getFloat("db_amt");
    cr_amt = results.getFloat("cr_amt");
    gl_type = results.getString("gl_type");
    gl_pct = results.getFloat("gl_pct");
                        out.println("<BODY bgColor=blanchedalmond text=#008000 topMargin=0>");
                        out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia > <BIG>GL MASTER INFORMATION</BIG></FONT></P>");
                        out.println("<P align=center>");
                        out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");
                        out.println("<TR>");
                        out.println("<TD>Code No.</TD>");
                        out.println("<TD>Description</TD>");
                        out.println("<TD>Dr. Amount</TD>");
                        out.println("<TD>Cr. Amount</TD>");
                        out.println("<TD>Type</TD>");
                        out.println("<TD>Percentage</TD></TR>");
                        out.println("<tr><td>" + gl_code);
                        out.println("<td>" + gl_descr);
                        out.println("<td>" + db_amt);
                        out.println("<td>" + cr_amt);
                        out.println("<td>" + gl_type);
                        out.println("<td>" + gl_pct);
                   if(doneheading)
                        out.println("</table>");
                   else
                        out.println("No matches for " + Code);
              catch (SQLException s)
                   out.println("Dupliacte Entry<br>");
         catch (ClassNotFoundException err)
              out.println("Class loading error");
    %>
    </body>
    </html>
    error:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
    Generated servlet error:
    D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:100: incompatible types
    found : float
    required: java.lang.Float
    db_amt = results.getFloat("db_amt");
    ^
    An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
    Generated servlet error:
    D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:101: incompatible types
    found : float
    required: java.lang.Float
    cr_amt = results.getFloat("cr_amt");
    ^
    An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
    Generated servlet error:
    D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:103: incompatible types
    found : float
    required: java.lang.Float
    gl_pct = results.getFloat("gl_pct");
    ^
    3 errors
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:437)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:497)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:476)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:464)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.0.30 logs.
    Apache Tomcat/5.0.30

                   Float db_amt,cr_amt,gl_pct;
    found : float
    required: java.lang.Float
    db_amt = results.getFloat("db_amt");The messages are self-explainatory. You are having objects of type Float. and the ResultSet.getFloat() would return float.
    Cheers
    -P

  • Float Conversion

    I am passing 2 strings of data Social Security Number and a string to be parsed
    1) SSN 123456789
    2)String PH80.00 170915.76 AAE
    The string is parsed PH is extracted, 80.00 is extracted and 170915.76 is converted, however, it is converted to 170916.77. .01 is added to the value. Why does this occur? I think it has to do with the float. The code is as follows
    * Created on Jun 13, 2007
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package com.abbott.HRT.US018;
    * @author Administrator
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class TransformData {
         * The below Function is for handling Compensation Update Records
         */ 2 examples of string passed MI80.00 242050.00 AAE Output produced is 242050.00
    PH80.00 170915.76 AAE Output produced is 170915.77
         private String compensationUpdate(String sRecord) {
              //1.Map directly the source data to target data and make changes to below lengths.
              StringBuffer sBuf = new StringBuffer(sRecord);
              //          Correction : Make the length of sBuf equal to 21 in order to reduce the risk of runtime exception
              if (sBuf.length() < 21) {
                   while (sBuf.length() != 21) {
                        sBuf.append(' ');
              //2.     Schedule Hours : Format the data into "ZZ9.99" at position 3-8
              String substring = sBuf.substring(2, 8);
              substring = formatNumber(substring, 4, 6, 2);
              sBuf.replace(2, 8, substring);
              //3.     Base Rate : Format the data into "ZZZZZZ9.99" at position 9-29. The target position will be 9-18
              substring = null;
              substring = sBuf.substring(8, 29);
              substring = formatNumber(substring, 8, 10, 2);
              sBuf.replace(8, 18, substring.substring(0, 10));
              sBuf.delete(18, 29);
              //4.     Performance Rating : For now no mapping is defined
              //At last append 434 spaces to the record
              sBuf = appendSpaces(sBuf, 434);
              return sBuf.toString();
         * The below Function is for formatting numbers Records
         private String formatNumber(
              String input,
              int position,
              int length,
              int decPlaces)
              throws NumberFormatException {
              //17.08.2007 : If empty string has come, send back the same
              int int1 = input.lastIndexOf(' ');
              int int2 = input.length();
              if (int1 == int2) {
                   return input;
              // position = actual position of dec place (e.g.4 for ZZ9.99)
              //length = actual length (e.g. 6 for ZZ9.99)
              //decPlaces = (e.g. 2 for ZZ9.99)
              //First get the input converted into float and back so as to add a decimal sign if it does not exist
              float f;
              try {
                   f = Float.parseFloat(input);
              } catch (NumberFormatException ex) {
                   throw new NumberFormatException(
                        "Exception Occurred:" + ex.getMessage());
              StringBuffer sb = new StringBuffer(length);
              sb.insert(0, f);
              //Identify the position of decimal sign and then shift it gradually
              int index = sb.indexOf(".");
              if (index < position && index != -1) {
                   while (index < (position - 1)) {
                        sb.insert(0, " ");
                        index = sb.indexOf(".");
                   /*If there is no decimal sign, put one at the desired position                         
                                            if(index == -1){
                                                 int int1 = Integer.parseInt(input);
                                                 sb.ins;
                                                 sb.insert(position,".");
              //Fill blank spaces after decimal sign with zero
              while (sb.length() < length) {
                   sb.append("0");
              return sb.toString();
    The code is as follows

    Volume is not precision. You need to be precise and informative. This end is not served by simply dumping huge volumes of code or data into a help request. If you have a large, complicated test case that is breaking a program, try to trim it and make it as small as possible.
    This is useful for at least three reasons. One: being seen to invest effort in simplifying the question makes it more likely that you'll get an answer, Two: simplifying the question makes it more likely you'll get a useful answer. Three: In the process of refining your bug report, you may develop a fix or workaround yourself.
    -- http://www.catb.org/~esr/faqs/smart-questions.html
    Example:
    assert 170915.77F == Float.parseFloat("170915.76"); // why?And here's the answer:
    http://en.wikipedia.org/wiki/Floating_point
    http://java.sun.com/developer/JDCTechTips/2003/tt0204.html#2
    http://docs.sun.com/source/806-3568/ncg_goldberg.html
    Cheers!
    ~

  • Float value giving exception.

    Hi,
    I am using a bean for a shopping cart. I used this code
    public float getCost()
              Enumeration enum=hashtable.elements();
              String[] tmpItem;
              float totalCost=0.00f;
              while(enum.hasMoreElements())
                   tmpItem=(String[])enum.nextElement();
                   //totalCost += (Integer.parseInt(tmpItem[3]) * Float.parseFloat(tmpItem[2]));
                   totalCost += (Integer.parseInt(tmpItem[3]) * Float.parseFloat(tmpItem[2]));
              return totalCost;
    which is giving me this exception.
    reported this exception: java.lang.Float: method parseFloat(Ljava/lang/String;)F not found. Please report this to the
    administrator of the web server.
    java.lang.NoSuchMethodError: java.lang.Float: method parseFloat(Ljava/lang/String;)F not found at
    ShopBean.getCost(Compiled Code) at Checkout.doGet(Checkout.java:20) at
    javax.servlet.http.HttpServlet.service(HttpServlet.java:715) at
    javax.servlet.http.HttpServlet.service(Compiled Code) at
    com.sun.server.ServletState.callService(Compiled Code) at
    com.sun.server.ServletManager.callServletService(Compiled Code) at
    com.sun.server.http.servlet.InvokerServlet.service(Compiled Code) at
    javax.servlet.http.HttpServlet.service(Compiled Code) at
    com.sun.server.ServletState.callService(Compiled Code) at
    com.sun.server.ServletManager.callServletService(Compiled Code) at
    com.sun.server.ProcessingState.invokeTargetServlet(Compiled Code) at
    com.sun.server.http.HttpProcessingState.execute(Compiled Code) at
    com.sun.server.http.stages.Runner.process(Compiled Code) at
    com.sun.server.ProcessingSupport.process(Compiled Code) at com.sun.server.Service.process(Compiled
    Code) at com.sun.server.http.HttpServiceHandler.handleRequest(Compiled Code) at
    com.sun.server.http.HttpServiceHandler.handleRequest(Compiled Code) at
    com.sun.server.HandlerThread.run(Compiled Code)
    Can any one correct me please?
    Thanks
    Uma

    Hi
    Here is the code which will be calling the bean
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    public class Checkout extends HttpServlet
         String itemsvalues,itemno;
         String[] tmpItem;
         public void doGet(HttpServletRequest req,HttpServletResponse res)
              try
                   ServletOutputStream sos = res.getOutputStream();
                   ShopBean cart =(ShopBean)req.getSession().getValue("cart");
                   int totalItems = cart.getNumOfItems();
                   System.out.println("totalItems="+totalItems);
                   sos.println("<h4>In Checkout.java</h4>");
                   float totalCost = cart.getCost();
                   sos.println("<h5>Total cost is:"+totalCost+"</h5>");
              catch(Exception e)
                   e.printStackTrace();
    This class is giving me exceptions
    Thanks
    Uma

  • Error in mapping for floating Number calculation

    Hi All,
       I have a small doubt in floating number calculation in Mapping.
    Actually i am geting a floating point number and calculating the SUM and generating the output. The input is of 2 decimal places(Ex: 26.02  and 26.03 ), but when it is adding all the values it is generating a three digit decimal number (Ex: 52.050003)
    I dont know from where it is geting one extra number "2" in the output.
    Please find the code for the same and let me know if i need to do something else to get ride of this.
       //write your code here
    float sum=0;
    if(a != null && a.length > 0.00)
       for ( int j =0; j<a.length;j++)
        sum  =  sum + Float.parseFloat(a[j]);
       result.addValue(String.valueOf(sum));
    else
    result.addValue("0");
    Thanks in Advance,
    JAY

    Jay,
    Please use the below code and let us know, if it helps.
    BigDecimal sum= new BigDecimal("0");
    BigDecimal bd;
    if(a != null && a.length > 0.00)
    for ( int j =0; j<a.length;j++)
    bd=new BigDecimal(a[j]);
    sum=sum.add(bd);
    result.addValue(""+sum+"");
    else
    result.addValue("0");
    in import section - java.math.*;
    raj.
    Edited by: Raj on Feb 18, 2008 11:11 AM

  • Problem in Converting string to float

    Hi,
    I am reading from textField and trying to convert that string value to float.
    Compiler is giving error cannot find symbol toFloat even though I have included java.lang in my program.
    Please help me with this one.
    Thanks.

    Use
    float f = Float.parseFloat(inputString); //where inputString is the string you want to parse

  • How to extract an integer or a float value from a String of characters

    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above String
    This is all i have so far:
    String c;
    String Array[] =new String[g]; (i used a while loop to obtain g(the nubmer of lines in the file))
    while((c=(cr.readLine()))!=null)
    Array[coun]=c;
    it would be reallllllllllllllllllllllllllllllllllllllly easy if there was a predefined method to extract numeric values from a string in java..
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:55 PM

    badmash wrote:
    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    with the space included
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above StringHuh?
    Not true.
    Anyway why not use string split, split on spaces and grab the last element (which by the format you posted would be your 700.0)
    Then there is the Float.parseFloat method.
    It is easy.
    And another thing why not use a List of Strings if you want to store each line? (And why did you post that code which doesn't really have anything to do with your problem?) Also in future please use the code formatting tags when posting code. Select the code you are posting in the message box and click the CODE button.

Maybe you are looking for