Example usage for java.lang Float Float

List of usage examples for java.lang Float Float

Introduction

In this page you can find the example usage for java.lang Float Float.

Prototype

@Deprecated(since = "9")
public Float(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Usage

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static Object readObjectFromXml(Element node) throws Exception {
    String nodeName = node.getNodeName();
    String nodeValue = ((Element) node).getAttribute("value");

    if (nodeName.equals("java.lang.Boolean")) {
        return new Boolean(nodeValue);
    } else if (nodeName.equals("java.lang.Byte")) {
        return new Byte(nodeValue);
    } else if (nodeName.equals("java.lang.Character")) {
        return new Character(nodeValue.charAt(0));
    } else if (nodeName.equals("java.lang.Integer")) {
        return new Integer(nodeValue);
    } else if (nodeName.equals("java.lang.Double")) {
        return new Double(nodeValue);
    } else if (nodeName.equals("java.lang.Float")) {
        return new Float(nodeValue);
    } else if (nodeName.equals("java.lang.Long")) {
        return new Long(nodeValue);
    } else if (nodeName.equals("java.lang.Short")) {
        return new Short(nodeValue);
    } else if (nodeName.equals("java.lang.String")) {
        return nodeValue;
    } else if (nodeName.equals("array")) {
        String className = node.getAttribute("classname");
        String length = node.getAttribute("length");
        int len = (new Integer(length)).intValue();

        Object array;//from w ww  .  ja  v  a  2  s . co  m
        if (className.equals("byte")) {
            array = new byte[len];
        } else if (className.equals("boolean")) {
            array = new boolean[len];
        } else if (className.equals("char")) {
            array = new char[len];
        } else if (className.equals("double")) {
            array = new double[len];
        } else if (className.equals("float")) {
            array = new float[len];
        } else if (className.equals("int")) {
            array = new int[len];
        } else if (className.equals("long")) {
            array = new long[len];
        } else if (className.equals("short")) {
            array = new short[len];
        } else {
            array = Array.newInstance(Class.forName(className), len);
        }

        Node xmlNode = null;
        NodeList nl = node.getChildNodes();
        int len_nl = nl.getLength();
        int i = 0;
        for (int j = 0; j < len_nl; j++) {
            xmlNode = nl.item(j);
            if (xmlNode.getNodeType() == Node.ELEMENT_NODE) {
                Object o = XMLUtils.readObjectFromXml((Element) xmlNode);
                Array.set(array, i, o);
                i++;
            }
        }

        return array;
    }
    // XMLization
    else if (nodeName.equals("xmlizable")) {
        String className = node.getAttribute("classname");

        Node xmlNode = findChildNode(node, Node.ELEMENT_NODE);
        Object xmlizable = Class.forName(className).newInstance();
        ((XMLizable) xmlizable).readXml(xmlNode);

        return xmlizable;
    }
    // Serialization
    else if (nodeName.equals("serializable")) {
        Node cdata = findChildNode(node, Node.CDATA_SECTION_NODE);
        String objectSerializationData = cdata.getNodeValue();
        Engine.logEngine.debug("Object serialization data:\n" + objectSerializationData);
        byte[] objectBytes = org.apache.commons.codec.binary.Base64.decodeBase64(objectSerializationData);

        // We read the object to a bytes array
        ByteArrayInputStream inputStream = new ByteArrayInputStream(objectBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        Object object = objectInputStream.readObject();
        inputStream.close();

        return object;
    }

    return null;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Float[] subsetFloatVector(InputStream in, int column, int numCases) {
    Float[] retVector = new Float[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            // Verified: new Float("nan") works correctly, 
            // resulting in Float.NaN;
            // Float("[+-]Inf") doesn't work however; 
            // (the constructor appears to be expecting it
            // to be spelled as "Infinity", "-Infinity", etc. 
            if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.POSITIVE_INFINITY;
            } else if ("-inf".equalsIgnoreCase(line[column])) {
                retVector[caseIndex] = java.lang.Float.NEGATIVE_INFINITY;
            } else if (line[column] == null || line[column].equals("")) {
                // missing value:
                retVector[caseIndex] = null;
            } else {
                try {
                    retVector[caseIndex] = new Float(line[column]);
                } catch (NumberFormatException ex) {
                    retVector[caseIndex] = null; // missing value
                }//  w  w w  .j  a v a 2s .  c o m
            }
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:BQJDBC.QueryResultTest.BQResultSetFunctionTest.java

@Test
public void TestResultSetgetFloat() {
    try {//from  ww w. j av a 2 s  .c  om
        Assert.assertTrue(BQResultSetFunctionTest.Result.absolute(1));
        Assert.assertEquals(new Float(42), BQResultSetFunctionTest.Result.getFloat(2));
    } catch (SQLException e) {
        this.logger.error("SQLexception" + e.toString());
        Assert.fail("SQLException" + e.toString());
    }
}

From source file:models.Service.java

/**
 * ? <br/>/*from  ww w  .  ja  v  a  2 s .  c om*/
 * ??
 * @param score
 */
public void computeAverageScore(Long toCommentUserId, Long serviceId) {
    this.score = new Float(
            Comment.getTotalLevelBytoCommentServiceId(toCommentUserId, serviceId, ServiceComment.class));
    this.commentNum = Comment.getTotalCountBytoCommentServiceId(toCommentUserId, serviceId,
            ServiceComment.class);
    DecimalFormat df = new DecimalFormat("###.0");
    if (commentNum != null && commentNum > 0)
        this.averageScore = Float.parseFloat(df.format((float) this.score / (float) this.commentNum));
}

From source file:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Extract the OUT parameter values from the callable statment and
 * assign them to the value of the parameter.
 *//*from   w w w. j  ava  2 s  .c  o m*/
public void extract(ConnectionContext cc, CallableStatement stmt) throws SQLException {
    if (getType().getValueIndex() == StoredProcedureParameter.Type.IN)
        return;

    int index = this.getIndex();
    QueryParameterType paramType = getSqlType();
    int jdbcType = paramType.getJdbcType();
    String identifier = paramType.getIdentifier();

    // result sets are special
    if (identifier.equals(QueryParameterType.RESULTSET_IDENTIFIER)) {
        ResultSet rs = (ResultSet) stmt.getObject(index);
        QueryResultSet qrs = new QueryResultSet(getParent().getProcedure(), cc, rs);
        value.getValue(cc).setValue(qrs);
        return;
    }

    switch (jdbcType) {
    case Types.VARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case Types.INTEGER:
        value.getValue(cc).setValue(new Integer(stmt.getInt(index)));
        break;
    case Types.DOUBLE:
        value.getValue(cc).setValue(new Double(stmt.getDouble(index)));
        break;
    case Types.CLOB:
        Clob clob = stmt.getClob(index);
        value.getValue(cc).setTextValue(clob.getSubString(1, (int) clob.length()));
        break;
    case java.sql.Types.ARRAY:
        Array array = stmt.getArray(index);
        value.getValue(cc).setValue(array);
        break;
    case java.sql.Types.BIGINT:
        long bigint = stmt.getLong(index);
        value.getValue(cc).setValue(new Long(bigint));
        break;
    case java.sql.Types.BINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.BIT:
        boolean bit = stmt.getBoolean(index);
        value.getValue(cc).setValue(new Boolean(bit));
    case java.sql.Types.BLOB:
        value.getValue(cc).setValue(stmt.getBlob(index));
        break;
    case java.sql.Types.CHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case java.sql.Types.DATE:
        value.getValue(cc).setValue(stmt.getDate(index));
        break;
    case java.sql.Types.DECIMAL:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.DISTINCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.FLOAT:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    case java.sql.Types.JAVA_OBJECT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.LONGVARBINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.LONGVARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    //case java.sql.Types.NULL:
    //    value.getValue(cc).setValue(null);
    //    break;
    case java.sql.Types.NUMERIC:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.OTHER:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.REAL:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    //case java.sql.Types.REF:
    //    Ref ref = stmt.getRef(index);
    //    break;
    case java.sql.Types.SMALLINT:
        short sh = stmt.getShort(index);
        value.getValue(cc).setValue(new Short(sh));
        break;
    case java.sql.Types.STRUCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.TIME:
        value.getValue(cc).setValue(stmt.getTime(index));
        break;
    case java.sql.Types.TIMESTAMP:
        value.getValue(cc).setValue(stmt.getTimestamp(index));
        break;
    case java.sql.Types.TINYINT:
        byte b = stmt.getByte(index);
        value.getValue(cc).setValue(new Byte(b));
        break;
    case java.sql.Types.VARBINARY:
        value.getValue(cc).setValue(stmt.getBytes(index));
        break;
    default:
        throw new RuntimeException(
                "Unknown JDBC Type set for stored procedure parameter '" + this.getName() + "'.");
    }
}

From source file:com.isencia.passerelle.message.TokenHelper.java

/**
 * Tries to get a Float from the token, by:
 * <ul>/*from   w  w  w  .ja v  a 2  s .c  om*/
 * <li>checking if the token is not an ObjectToken, containing a Float
 * <li>checking if the token is not an ObjectToken, and converting the object.toString() into a Float
 * <li>checking if the token is not a StringToken, and converting the string into a Float
 * <li>checking if the token is not a ScalarToken, and reading its double value and converting it to a float
 * </ul>
 * Remark that converting a double to a float may lead to loss of precision. Furthermore, if the double value in the
 * token is bigger than Float.MAX_VALUE, the converted float will just be "infinity".
 * 
 * @param token
 * @return
 */
public static Float getFloatFromToken(Token token) throws PasserelleException {
    if (logger.isTraceEnabled()) {
        logger.trace(token.toString()); // TODO Check if correct converted
    }
    Float res = null;

    if (token != null) {
        try {
            if (token instanceof ObjectToken) {
                Object obj = ((ObjectToken) token).getValue();
                if (obj instanceof Float) {
                    res = (Float) obj;
                } else if (obj != null) {
                    try {
                        res = Float.valueOf(obj.toString());
                    } catch (NumberFormatException e) {
                        throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                "Invalid Float format in " + token, e);
                    }
                }
            } else {
                if (token instanceof StringToken) {
                    String tokenMessage = ((StringToken) token).stringValue();
                    if (tokenMessage != null) {
                        try {
                            res = Float.valueOf(tokenMessage);
                        } catch (NumberFormatException e) {
                            throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                    "Invalid Float format in " + token, e);
                        }
                    }
                } else if (token instanceof ScalarToken) {
                    try {
                        res = new Float(((ScalarToken) token).doubleValue());
                    } catch (IllegalActionException e) {
                        throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                                "Invalid token for obtaining Float value in " + token, e);
                    }
                } else {
                    throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                            "Invalid token for obtaining Float value in " + token, null);
                }
            }
        } catch (Exception e) {
            throw new PasserelleException(ErrorCode.MSG_CONTENT_TYPE_ERROR,
                    "Error building Float from token in " + token, e);
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("exit :" + res);
    }
    return res;
}

From source file:edu.hawaii.soest.hioos.isus.ISUSFrame.java

public double getSpectrometerAverage() {
    this.spectrometerAverage.flip();
    return (new Float(this.spectrometerAverage.getFloat())).doubleValue();
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.mapofscience.MapOfScienceVisualizationRequestHandler.java

private String getDisciplineToPublicationsCSVContent(Entity subjectEntity) {

    StringBuilder csvFileContent = new StringBuilder();

    csvFileContent.append("Discipline, Publication Count, % Activity\n");

    PublicationJournalStats stats = extractScienceMappingResultFromActivities(subjectEntity);
    ScienceMappingResult result = stats.scienceMapping;

    Map<Integer, Float> disciplineToPublicationCount = new HashMap<Integer, Float>();

    Float totalMappedPublications = new Float(0);

    if (result != null) {

        for (Map.Entry<Integer, Float> currentMappedSubdiscipline : result.getMappedResult().entrySet()) {

            float updatedPublicationCount = currentMappedSubdiscipline.getValue();

            Integer lookedUpDisciplineID = MapOfScienceConstants.SUB_DISCIPLINE_ID_TO_DISCIPLINE_ID
                    .get(currentMappedSubdiscipline.getKey());

            if (disciplineToPublicationCount.containsKey(lookedUpDisciplineID)) {

                updatedPublicationCount += disciplineToPublicationCount.get(lookedUpDisciplineID);
            }/*  w ww. j  av  a 2  s .com*/

            disciplineToPublicationCount.put(lookedUpDisciplineID, updatedPublicationCount);
        }

        totalMappedPublications = result.getMappedPublications();
    }

    DecimalFormat percentageActivityFormat = new DecimalFormat("#.#");

    for (Map.Entry<Integer, Float> currentMappedDiscipline : disciplineToPublicationCount.entrySet()) {

        csvFileContent.append(StringEscapeUtils
                .escapeCsv(MapOfScienceConstants.DISCIPLINE_ID_TO_LABEL.get(currentMappedDiscipline.getKey())));
        csvFileContent.append(", ");
        csvFileContent.append(percentageActivityFormat.format(currentMappedDiscipline.getValue()));
        csvFileContent.append(", ");

        if (totalMappedPublications > 0) {
            csvFileContent.append(percentageActivityFormat
                    .format(100 * currentMappedDiscipline.getValue() / totalMappedPublications));
        } else {
            csvFileContent.append("Not Available");
        }

        csvFileContent.append("\n");
    }

    for (Map.Entry<Integer, String> currentDiscipline : MapOfScienceConstants.DISCIPLINE_ID_TO_LABEL
            .entrySet()) {

        Float currentDisciplineValue = disciplineToPublicationCount.get(currentDiscipline.getKey());
        if (currentDisciplineValue == null) {

            csvFileContent.append(StringEscapeUtils.escapeCsv(currentDiscipline.getValue()));
            csvFileContent.append(", ");
            csvFileContent.append(0);
            csvFileContent.append(", ");
            csvFileContent.append(0);
            csvFileContent.append("\n");

        }
    }

    return csvFileContent.toString();
}

From source file:org.hdiv.web.servlet.tags.form.OptionTagTests.java

protected void extendRequest(MockHttpServletRequest request) {
    TestBean bean = new TestBean();
    bean.setName("foo");
    bean.setFavouriteColour(Colour.GREEN);
    bean.setStringArray(ARRAY);/*from w w w .  ja  v a  2  s. c o  m*/
    bean.setSpouse(new TestBean("Sally"));
    bean.setSomeNumber(new Float("12.34"));

    List friends = new ArrayList();
    friends.add(new TestBean("bar"));
    friends.add(new TestBean("penc"));
    bean.setFriends(friends);

    request.setAttribute("testBean", bean);
    request.setAttribute("myNumber", new Float(12.34));
    request.setAttribute("myOtherNumber", new Float(12.35));
}

From source file:BQJDBC.QueryResultTest.BQScrollableResultSetFunctionTest.java

@Test
public void TestResultSetgetFloat() {
    try {/*from w w w.java2s . c  o  m*/
        Assert.assertTrue(BQScrollableResultSetFunctionTest.Result.absolute(1));
        Assert.assertEquals(new Float(42), BQScrollableResultSetFunctionTest.Result.getFloat(2));
    } catch (SQLException e) {
        this.logger.error("SQLexception" + e.toString());
        Assert.fail("SQLException" + e.toString());
    }
}