Example usage for java.lang Number doubleValue

List of usage examples for java.lang Number doubleValue

Introduction

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

Prototype

public abstract double doubleValue();

Source Link

Document

Returns the value of the specified number as a double .

Usage

From source file:edu.brown.utils.CollectionUtil.java

/**
 * Convert a Collection of Numbers to an array of primitive doubles
 * Null values will be skipped in the array 
 * @param items/*from   w ww .  j a va2s .  co  m*/
 * @return
 */
public static double[] toDoubleArray(Collection<? extends Number> items) {
    double ret[] = new double[items.size()];
    int idx = 0;
    for (Number n : items) {
        if (n != null)
            ret[idx] = n.doubleValue();
        idx += 1;
    } // FOR
    return (ret);
}

From source file:nz.co.senanque.validationengine.ConvertUtils.java

public static Comparable<?> convertTo(Class<?> clazz, Object obj) {
    if (obj == null) {
        return null;
    }//from ww  w  . ja va  2s .c  o m
    if (clazz.isAssignableFrom(obj.getClass())) {
        return (Comparable<?>) obj;
    }
    if (clazz.isPrimitive()) {
        if (clazz.equals(Long.TYPE)) {
            clazz = Long.class;
        } else if (clazz.equals(Integer.TYPE)) {
            clazz = Integer.class;
        } else if (clazz.equals(Float.TYPE)) {
            clazz = Float.class;
        } else if (clazz.equals(Double.TYPE)) {
            clazz = Double.class;
        } else if (clazz.equals(Boolean.TYPE)) {
            clazz = Boolean.class;
        }
    }
    if (Number.class.isAssignableFrom(clazz)) {
        if (obj.getClass().equals(String.class)) {
            obj = new Double((String) obj);
        }
        if (!Number.class.isAssignableFrom(obj.getClass())) {
            throw new RuntimeException(
                    "Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
        }
        Number number = (Number) obj;
        if (clazz.equals(Long.class)) {
            return new Long(number.longValue());
        }
        if (clazz.equals(Integer.class)) {
            return new Integer(number.intValue());
        }
        if (clazz.equals(Float.class)) {
            return new Float(number.floatValue());
        }
        if (clazz.equals(Double.class)) {
            return new Double(number.doubleValue());
        }
        if (clazz.equals(BigDecimal.class)) {
            return new BigDecimal(number.doubleValue());
        }
    }
    final String oStr = String.valueOf(obj);
    if (clazz.equals(String.class)) {
        return oStr;
    }
    if (clazz.equals(java.util.Date.class)) {
        return java.sql.Date.valueOf(oStr);
    }
    if (clazz.equals(java.sql.Date.class)) {
        return java.sql.Date.valueOf(oStr);
    }
    if (clazz.equals(Boolean.class)) {
        return new Boolean(oStr);
    }
    throw new RuntimeException("Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
}

From source file:de.cebitec.readXplorer.util.GeneralUtils.java

/**
 * Converts a given number into a number of the given classType. If this is
 * not possible, it throws a ClassCastException
 * @param <T> one of the classes derived from Number
 * @param classType the type to convert the number into
 * @param number the number to convert//from w  w  w.  j a v a2  s.  co  m
 * @return The converted number
 */
public static <T extends Number> T convertNumber(Class<T> classType, Number number) throws ClassCastException {
    T convertedValue = null;
    if (classType.equals(Integer.class)) {
        convertedValue = classType.cast(number.intValue());
    } else if (classType.equals(Double.class)) {
        convertedValue = classType.cast(number.doubleValue());
    } else if (classType.equals(Long.class)) {
        convertedValue = classType.cast(number.longValue());
    } else if (classType.equals(Float.class)) {
        convertedValue = classType.cast(number.floatValue());
    } else if (classType.equals(Short.class)) {
        convertedValue = classType.cast(number.shortValue());
    } else if (classType.equals(Byte.class)) {
        convertedValue = classType.cast(number.byteValue());
    }

    if (convertedValue == null) {
        throw new ClassCastException("Cannot cast the given number into the given format.");
    }

    return convertedValue;
}

From source file:gov.nasa.jpf.constraints.solvers.cw.CWSolver.java

static double computeError(NumericComparator comparator, Number value) {
    return computeError(comparator, value.doubleValue());
}

From source file:net.refractions.udig.style.sld.editor.raster.SingleBandEditorPage.java

public static final void sortEntries(ColorMapEntry[] entries) {
    Arrays.sort(entries, new Comparator<ColorMapEntry>() {

        @Override//from  w w  w . j  a  v  a2  s. co m
        public int compare(ColorMapEntry c0, ColorMapEntry c1) {
            Number v1 = (Number) c0.getQuantity().evaluate(null, Double.class);
            Number v2 = (Number) c1.getQuantity().evaluate(null, Double.class);
            return ((Double) v1.doubleValue()).compareTo(v2.doubleValue());
        }
    });
}

From source file:org.hxzon.demo.jfreechart.PieDatasetDemo2.java

private static JFreeChart createPieChart(PieDataset dataset, PieDataset previousDataset) {
    final boolean greenForIncrease = true;
    final boolean subTitle = true;
    final boolean showDifference = true;
    int percentDiffForMaxScale = 20;
    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator());
    }//from  w  w w.  jav a2  s . c o m
    if (urls) {
        plot.setURLGenerator(new StandardPieURLGenerator());
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    List<Comparable> keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (@SuppressWarnings("rawtypes")
    Comparable key : keys) {
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart("Pie Chart Demo 2", JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    plot.setNoDataMessage("No data available");

    return chart;

}

From source file:com.alibaba.wasp.plan.parser.druid.DruidParser.java

/**
 * The abstract class Number is the superclass of classes BigDecimal,
 * BigInteger, Byte, Double, Float, Integer, Long, and Short. Subclasses of
 * Number must provide methods to convert the represented numeric value to
 * byte, double, float, int, long, and short.
 *//*from ww w  . j a v  a  2  s.  c  o m*/
public static byte[] convert(DataType type, Number number) throws UnsupportedException {
    // BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
    if (number instanceof BigDecimal) {
        if (type == DataType.FLOAT) {
            return Bytes.toBytes(number.floatValue());
        } else if (type == DataType.DOUBLE) {
            return Bytes.toBytes(number.doubleValue());
        } else if (type == DataType.INT32) {
            return Bytes.toBytes(number.intValue());
        } else if (type == DataType.INT64) {
            return Bytes.toBytes(number.longValue());
        }
        return Bytes.toBytes((BigDecimal) number);
    } else if (number instanceof BigInteger) {
        throw new UnsupportedException(" BigInteger " + number + " Unsupported");
    } else if (number instanceof Byte) {
        return Bytes.toBytes((Byte) number);
    } else if (number instanceof Double) {
        double value = number.doubleValue();
        if (type == DataType.FLOAT) {
            return Bytes.toBytes((float) value);
        } else if (type == DataType.DOUBLE) {
            return Bytes.toBytes(value);
        } else if (type == DataType.INT32) {
            int iv = (int) value;
            return Bytes.toBytes(iv);
        } else if (type == DataType.INT64) {
            long lv = (long) value;
            return Bytes.toBytes(lv);
        }
    } else if (number instanceof Float) {
        float value = number.floatValue();
        if (type == DataType.FLOAT) {
            return Bytes.toBytes(value);
        } else if (type == DataType.DOUBLE) {
            return Bytes.toBytes((float) value);
        } else if (type == DataType.INT32) {
            int iv = (int) value;
            return Bytes.toBytes(iv);
        } else if (type == DataType.INT64) {
            long lv = (long) value;
            return Bytes.toBytes(lv);
        }
    } else if (number instanceof Integer) {
        int value = number.intValue();
        if (type == DataType.INT32) {
            return Bytes.toBytes((Integer) value);
        } else if (type == DataType.INT64) {
            return Bytes.toBytes((long) value);
        } else if (type == DataType.FLOAT) {
            float fv = (float) value;
            return Bytes.toBytes(fv);
        } else if (type == DataType.DOUBLE) {
            double fv = (double) value;
            return Bytes.toBytes(fv);
        }
    } else if (number instanceof Long) {
        long value = number.longValue();
        if (type == DataType.INT32) {
            return Bytes.toBytes((int) value);
        } else if (type == DataType.INT64) {
            return Bytes.toBytes(value);
        } else if (type == DataType.FLOAT) {
            float fv = (float) value;
            return Bytes.toBytes(fv);
        } else if (type == DataType.DOUBLE) {
            double fv = (double) value;
            return Bytes.toBytes(fv);
        }
    } else if (number instanceof Short) {
        return Bytes.toBytes((Short) number);
    }
    throw new UnsupportedException("Unknown Number:" + number + " Type:" + type + " Unsupported ");
}

From source file:com.feilong.core.lang.NumberUtil.java

/**
 * .// w  w w  .j a  va  2  s  .co m
 * 
 * <pre class="code">
 * NumberUtil.getProgress(5, 5, NumberPattern.PERCENT_WITH_NOPOINT) =   100%
 * NumberUtil.getProgress(2, 3, NumberPattern.PERCENT_WITH_1POINT)  =   66.7%
 * </pre>
 *
 * @param current
 *            ??
 * @param total
 *            ?
 * @param numberPattern
 *            the number pattern {@link NumberPattern}
 * @return  <code>current</code> null, {@link NullPointerException}<br>
 *          <code>total</code> null, {@link NullPointerException}<br>
 *          {@code current<=0}, {@link IllegalArgumentException}<br>
 *          {@code total<=0}, {@link IllegalArgumentException}<br>
 *          {@code current>total}, {@link IllegalArgumentException}<br>
 * @see NumberPattern
 * @see #getDivideValue(Number, Number, int)
 * @since 1.0.7
 */
public static String getProgress(Number current, Number total, String numberPattern) {
    Validate.notNull(current, "current can't be null/empty!");
    Validate.notNull(total, "total can't be null/empty!");

    Validate.isTrue(current.intValue() > 0, "current can not <=0");
    Validate.isTrue(total.intValue() > 0, "total can not <=0");
    Validate.isTrue(current.doubleValue() <= total.doubleValue(), "current can not > total");

    // XXX  scale = 8?
    int scale = 8;
    BigDecimal bigDecimalCurrent = toBigDecimal(current);
    BigDecimal divideValue = getDivideValue(bigDecimalCurrent, total, scale);
    return toString(divideValue, numberPattern);
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules://from  w w w .  j av  a  2 s  .c om
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules://w  ww . j  a va 2  s. c om
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}