Example usage for java.lang Number floatValue

List of usage examples for java.lang Number floatValue

Introduction

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

Prototype

public abstract float floatValue();

Source Link

Document

Returns the value of the specified number as a float .

Usage

From source file:NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 * @param number the number to convert/*from   ww  w . ja  va2  s  . co m*/
 * @param targetClass the target class to convert to
 * @return the converted number
 * @throws IllegalArgumentException if the target class is not supported
 * (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte
 * @see java.lang.Short
 * @see java.lang.Integer
 * @see java.lang.Long
 * @see java.math.BigInteger
 * @see java.lang.Float
 * @see java.lang.Double
 * @see java.math.BigDecimal
 */
public static Number convertNumberToTargetClass(Number number, Class targetClass)
        throws IllegalArgumentException {

    if (targetClass.isInstance(number)) {
        return number;
    } else if (targetClass.equals(Byte.class)) {
        long value = number.longValue();
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Byte(number.byteValue());
    } else if (targetClass.equals(Short.class)) {
        long value = number.longValue();
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Short(number.shortValue());
    } else if (targetClass.equals(Integer.class)) {
        long value = number.longValue();
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Integer(number.intValue());
    } else if (targetClass.equals(Long.class)) {
        return new Long(number.longValue());
    } else if (targetClass.equals(Float.class)) {
        return new Float(number.floatValue());
    } else if (targetClass.equals(Double.class)) {
        return new Double(number.doubleValue());
    } else if (targetClass.equals(BigInteger.class)) {
        return BigInteger.valueOf(number.longValue());
    } else if (targetClass.equals(BigDecimal.class)) {
        // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
        // (see BigDecimal javadoc for details)
        return new BigDecimal(number.toString());
    } else {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
                + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
    }
}

From source file:net.sf.jasperreports.engine.util.JRFloatLocaleConverter.java

@Override
protected Object parse(Object value, String pattern) throws ParseException {
    final Number parsed = (Number) super.parse(value, pattern);
    double doubleValue = parsed.doubleValue();
    double posDouble = (doubleValue >= 0) ? doubleValue : (doubleValue * -1);
    if ((posDouble > 0 && posDouble < Float.MIN_VALUE) || posDouble > Float.MAX_VALUE) {
        throw new ConversionException("Supplied number is not of type Float: " + parsed);
    }//  w ww . j  a v  a 2  s .  c o  m
    return parsed.floatValue(); // unlike superclass it returns Float type
}

From source file:org.apache.fontbox.cff.Type1CharString.java

/**
 * Relative moveto.//from w  ww  . j a va2s .  c  o  m
 */
private void rmoveTo(Number dx, Number dy) {
    float x = (float) current.getX() + dx.floatValue();
    float y = (float) current.getY() + dy.floatValue();
    path.moveTo(x, y);
    current.setLocation(x, y);
}

From source file:org.apache.fontbox.cff.Type1CharString.java

/**
 * Relative lineto.//from  w  w  w  .j a v  a  2  s.c  om
 */
private void rlineTo(Number dx, Number dy) {
    float x = (float) current.getX() + dx.floatValue();
    float y = (float) current.getY() + dy.floatValue();
    if (path.getCurrentPoint() == null) {
        LOG.warn("rlineTo without initial moveTo in font " + fontName + ", glyph " + glyphName);
        path.moveTo(x, y);
    } else {
        path.lineTo(x, y);
    }
    current.setLocation(x, y);
}

From source file:LineGraphDrawable.java

/**
 * Draws the bar-graph into the given Graphics2D context in the given area.
 * This method will not draw a graph if the data given is null or empty.
 * //w ww .  j  av  a2s.c  om
 * @param graphics
 *          the graphics context on which the bargraph should be rendered.
 * @param drawArea
 *          the area on which the bargraph should be drawn.
 */
public void draw(final Graphics2D graphics, final Rectangle2D drawArea) {
    if (graphics == null) {
        throw new NullPointerException();
    }
    if (drawArea == null) {
        throw new NullPointerException();
    }

    final int height = (int) drawArea.getHeight();
    if (height <= 0) {
        return;
    }

    final Graphics2D g2 = (Graphics2D) graphics.create();
    if (background != null) {
        g2.setPaint(background);
        g2.draw(drawArea);
    }

    if (data == null || data.length == 0) {
        g2.dispose();
        return;
    }

    g2.translate(drawArea.getX(), drawArea.getY());

    float d = getDivisor(data, height);
    final int spacing = getSpacing();
    final int w = (((int) drawArea.getWidth()) - (spacing * (data.length - 1))) / (data.length - 1);

    float min = Float.MAX_VALUE;
    for (int index = 0; index < data.length; index++) {
        Number i = data[index];
        if (i == null) {
            continue;
        }
        final float value = i.floatValue();
        if (value < min) {
            min = value;
        }
    }

    int x = 0;
    int y = -1;

    if (d == 0.0) {
        // special case -- a horizontal straight line
        d = 1.0f;
        y = -height / 2;
    }

    final Line2D.Double line = new Line2D.Double();
    for (int i = 0; i < data.length - 1; i++) {
        final int px1 = x;
        x += (w + spacing);
        final int px2 = x;

        g2.setPaint(color);

        final Number number = data[i];
        final Number nextNumber = data[i + 1];
        if (number == null && nextNumber == null) {
            final float delta = height - ((0 - min) / d);
            line.setLine(px1, y + delta, px2, y + delta);
        } else if (number == null) {
            line.setLine(px1, y + (height - ((0 - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        } else if (nextNumber == null) {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((0 - min) / d)));
        } else {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        }
        g2.draw(line);

    }

    g2.dispose();

}

From source file:com.googlecode.jmxtrans.model.output.StatsDTelegrafWriter.java

@Override
public void write(@Nonnull Writer writer, @Nonnull Server server, @Nonnull Query query,
        @Nonnull Iterable<Result> results) throws IOException {

    int resultIndex = -1;
    for (Result result : results) {
        resultIndex++;/*from   www  .  java 2s .  c o  m*/
        String bucketType = getBucketType(resultIndex);
        String attributeName = result.getAttributeName();

        List<String> resultTagList = new ArrayList<>();
        resultTagList.add(",jmxport=" + server.getPort());
        //tagList.add("objectName=" + query.getObjectName());
        resultTagList.add("attribute=" + attributeName);

        if (isNotValidValue(result.getValue())) {
            log.debug("Skipping message key[{}] with value: {}.", result.getAttributeName(), result.getValue());
            continue;
        }
        List<String> tagList = new ArrayList(resultTagList);

        if (!result.getValuePath().isEmpty()) {
            tagList.add("resultKey=" + KeyUtils.getValuePathString(result));
        }

        for (Map.Entry e : tags.entrySet()) {
            tagList.add(e.getKey() + "=" + e.getValue());
        }

        Number actualValue = computeActualValue(result.getValue());
        StringBuilder sb = new StringBuilder(result.getKeyAlias()).append(StringUtils.join(tagList, ","))
                .append(":").append(actualValue).append("|").append(bucketType).append("\n");

        String output = sb.toString();
        if (actualValue.floatValue() < 0 && !StatsDMetricType.GAUGE.getKey().equals(bucketType)) {
            log.debug("Negative values are only supported for gauges, not sending: {}.", output);
        } else {
            log.debug(output);
            writer.write(output);
        }
    }
}

From source file:org.apache.tajo.storage.json.JsonLineDeserializer.java

/**
 *
 *
 * @param object// w  w w.  j  a  v a 2s  . c om
 * @param pathElements
 * @param depth
 * @param fieldIndex
 * @param output
 * @throws IOException
 */
private void getValue(JSONObject object, String fullPath, String[] pathElements, int depth, int fieldIndex,
        Tuple output) throws IOException {
    String fieldName = pathElements[depth];

    if (!object.containsKey(fieldName)) {
        output.put(fieldIndex, NullDatum.get());
    }

    switch (types.get(fullPath)) {
    case BOOLEAN:
        String boolStr = object.getAsString(fieldName);
        if (boolStr != null) {
            output.put(fieldIndex, DatumFactory.createBool(boolStr.equals("true")));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case CHAR:
        String charStr = object.getAsString(fieldName);
        if (charStr != null) {
            output.put(fieldIndex, DatumFactory.createChar(charStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT1:
    case INT2:
        Number int2Num = object.getAsNumber(fieldName);
        if (int2Num != null) {
            output.put(fieldIndex, DatumFactory.createInt2(int2Num.shortValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT4:
        Number int4Num = object.getAsNumber(fieldName);
        if (int4Num != null) {
            output.put(fieldIndex, DatumFactory.createInt4(int4Num.intValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT8:
        Number int8Num = object.getAsNumber(fieldName);
        if (int8Num != null) {
            output.put(fieldIndex, DatumFactory.createInt8(int8Num.longValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case FLOAT4:
        Number float4Num = object.getAsNumber(fieldName);
        if (float4Num != null) {
            output.put(fieldIndex, DatumFactory.createFloat4(float4Num.floatValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case FLOAT8:
        Number float8Num = object.getAsNumber(fieldName);
        if (float8Num != null) {
            output.put(fieldIndex, DatumFactory.createFloat8(float8Num.doubleValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TEXT:
        String textStr = object.getAsString(fieldName);
        if (textStr != null) {
            output.put(fieldIndex, DatumFactory.createText(textStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TIMESTAMP:
        String timestampStr = object.getAsString(fieldName);
        if (timestampStr != null) {
            output.put(fieldIndex, DatumFactory.createTimestamp(timestampStr, timezone));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TIME:
        String timeStr = object.getAsString(fieldName);
        if (timeStr != null) {
            output.put(fieldIndex, DatumFactory.createTime(timeStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case DATE:
        String dateStr = object.getAsString(fieldName);
        if (dateStr != null) {
            output.put(fieldIndex, DatumFactory.createDate(dateStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case BIT:
    case BINARY:
    case VARBINARY:
    case BLOB: {
        Object jsonObject = object.getAsString(fieldName);

        if (jsonObject == null) {
            output.put(fieldIndex, NullDatum.get());
            break;
        }

        output.put(fieldIndex, DatumFactory.createBlob(Base64.decodeBase64((String) jsonObject)));
        break;
    }

    case RECORD:
        JSONObject nestedObject = (JSONObject) object.get(fieldName);
        if (nestedObject != null) {
            getValue(nestedObject, fullPath + "/" + pathElements[depth + 1], pathElements, depth + 1,
                    fieldIndex, output);
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;

    case NULL_TYPE:
        output.put(fieldIndex, NullDatum.get());
        break;

    default:
        throw new TajoRuntimeException(
                new NotImplementedException("" + types.get(fullPath).name() + " for json"));
    }
}

From source file:de.instantouch.model.io.SnakeJSONReader.java

public void read(SnakeType type, Object value) throws SnakeModelException, IOException, InstantiationException,
        IllegalAccessException, ClassNotFoundException {

    if (type.hasReference()) {
        SnakeReference ref = type.getReference();
        if (ref == null) {
            throw new SnakeNotInitializedException("reference is not initialized");
        }/*  w  w  w . ja  v  a2  s  .  c om*/

        SnakeType key = ref.getKey();
        if (key == null) {
            throw new SnakeNotInitializedException("no reference key container os given");
        }

        read(key, value);
    } else {
        if (type instanceof SnakeEntity) {
            readEntity((SnakeEntity) type, value);
        } else if (type instanceof SnakeList) {
            readList((SnakeList) type, value);
        } else if (type instanceof SnakeMap) {
            readMap((SnakeMap) type, value);
        } else if (value == null) {
            type.setNull();
        } else if (value instanceof String) {
            type.set(value.toString());
        } else if (value instanceof Boolean) {
            type.set(value.toString());
        } else if (value instanceof Number) {
            Number number = (Number) value;

            if (value instanceof Double) {
                type.set(number.doubleValue());
            } else if (value instanceof Float) {
                type.set(number.floatValue());
            } else if (value instanceof Byte) {
                type.set(number.byteValue());
            } else if (value instanceof Short) {
                type.set(number.shortValue());
            } else if (value instanceof Integer) {
                type.set(number.intValue());
            } else if (value instanceof Long) {
                type.set(number.longValue());
            }
        }
    }

}

From source file:org.apache.fontbox.cff.Type1CharString.java

/**
 * Relative curveto./*  w  w w . j a v a 2s .  co m*/
 */
private void rrcurveTo(Number dx1, Number dy1, Number dx2, Number dy2, Number dx3, Number dy3) {
    float x1 = (float) current.getX() + dx1.floatValue();
    float y1 = (float) current.getY() + dy1.floatValue();
    float x2 = x1 + dx2.floatValue();
    float y2 = y1 + dy2.floatValue();
    float x3 = x2 + dx3.floatValue();
    float y3 = y2 + dy3.floatValue();
    if (path.getCurrentPoint() == null) {
        LOG.warn("rrcurveTo without initial moveTo in font " + fontName + ", glyph " + glyphName);
        path.moveTo(x3, y3);
    } else {
        path.curveTo(x1, y1, x2, y2, x3, y3);
    }
    current.setLocation(x3, y3);
}

From source file:adams.ml.Dataset.java

protected String summariseNumeric(String columnname) {
    Vector<Float> vf = new Vector<>();
    Hashtable<Float, Boolean> ind = new Hashtable<>();
    int numErrors = 0;
    int missing = 0;
    int ignored = 0;
    for (int i = 0; i < count(); i++) {
        DataRow dr = get(i);//w  w w .j  ava2s . co  m
        if (dr.get(columnname) == null) {
            missing++;
            continue;
        }
        dr = getSafe(i);
        if (dr == null) {
            ignored++;
            continue;
        }
        try {
            Number val = (Number) dr.get(columnname).getData();
            vf.add(val.floatValue());
            if (ind.get(val.floatValue()) == null) {
                ind.put(val.floatValue(), true);
            }
        } catch (Exception e) {
            try {
                Float pi = Float.parseFloat(dr.getAsString(columnname));
                vf.add(pi);
            } catch (Exception e1) {
                numErrors++;
                continue;
            }
        }
    }
    double[] f = new double[vf.size()];
    for (int i = 0; i < f.length; i++) {
        f[i] = vf.get(i);
    }
    StringBuffer ret = new StringBuffer();
    ret.append("Total OK: " + vf.size() + "\n");
    ret.append("Ignored Rows: " + ignored + "\n");
    ret.append("Missing: " + missing + "\n");
    ret.append("Errors: " + numErrors + "\n");
    ret.append("Different: " + ind.size() + "\n");
    double min = StatUtils.min(f);
    double max = StatUtils.max(f);
    double mean = StatUtils.mean(f);
    double stdev = Math.sqrt(StatUtils.variance(f));
    double median = StatUtils.percentile(f, 50);
    ret.append("Min,Max: " + min + "," + max + "\n");
    ret.append("Mean: " + mean + "\n");
    ret.append("Standard Deviation: " + stdev + "\n");
    ret.append("Median: " + median + "\n");
    return (ret.toString());
}