Example usage for java.lang Number toString

List of usage examples for java.lang Number toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.amazonaws.hal.client.ConversionUtil.java

private static Object convertFromNumber(Class<?> clazz, Number value) {
    if (String.class.isAssignableFrom(clazz)) {
        return value.toString();
    } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) {
        return value.intValue();
    } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) {
        return value.longValue();
    } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) {
        return value.shortValue();
    } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) {
        return value.doubleValue();
    } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
        return value.floatValue();
    } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) {
        return Boolean.valueOf(value.toString());
    } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) {
        if (value.longValue() <= 255) {
            return (char) value.longValue();
        } else {/* ww w.  j  av  a 2 s  .c o  m*/
            throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
        }
    } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) {
        return value.byteValue();
    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
        return new BigDecimal(value.toString());
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to
        // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2)
        return new BigInteger(String.valueOf(value.longValue()));
    } else if (Date.class.isAssignableFrom(clazz)) {
        return new Date(value.longValue());
    } else if (clazz.isEnum()) {
        try {
            //noinspection unchecked
            return Enum.valueOf((Class<Enum>) clazz, value.toString());
        } catch (IllegalArgumentException e) {
            log.error(String.format(
                    "'%s' is not a recognized enum value for %s.  Returning default of %s instead.", value,
                    clazz.getName(), clazz.getEnumConstants()[0]));

            return clazz.getEnumConstants()[0];
        }
    } else {
        throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
    }
}

From source file:playground.benjamin.scenarios.zurich.analysis.charts.BkChartWriter.java

public static void writeChartDataToFile(String filename, JFreeChart chart) {
    filename += ".txt";
    try {//w  w w. j a va  2s.  c  o  m
        BufferedWriter writer = IOUtils.getBufferedWriter(filename);
        try { /*read "try" as if (plot instanceof XYPlot)*/
            XYPlot xy = chart.getXYPlot();
            String yAxisLabel = xy.getRangeAxis().getLabel();

            String xAxisLabel = "";
            if (xy.getDomainAxis() != null) {
                xAxisLabel = xy.getDomainAxis().getLabel();
            }
            String header = xAxisLabel + "\t " + yAxisLabel;
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < xy.getDatasetCount(); i++) {
                XYDataset xyds = xy.getDataset(i);
                for (int seriesIndex = 0; seriesIndex < xyds.getSeriesCount(); seriesIndex++) {
                    writer.newLine();
                    writer.write("Series " + "'" + xyds.getSeriesKey(seriesIndex).toString());
                    writer.write("'");
                    writer.newLine();
                    int items = xyds.getItemCount(seriesIndex);
                    for (int itemsIndex = 0; itemsIndex < items; itemsIndex++) {
                        Number xValue = xyds.getX(seriesIndex, itemsIndex);
                        Number yValue = xyds.getY(seriesIndex, itemsIndex);
                        writer.write(xValue.toString());
                        writer.write("\t");
                        writer.write(yValue.toString());
                        writer.newLine();
                    }
                }
            }
            System.out.println("Table written to : " + filename + "\n"
                    + "==================================================");

        } catch (ClassCastException e) { //else instanceof CategoryPlot
            log.info("caught class cast exception, trying to write CategoryPlot");
            CategoryPlot cp = chart.getCategoryPlot();
            String header = "CategoryRowKey \t CategoryColumnKey \t CategoryRowIndex \t CategoryColumnIndex \t Value";
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < cp.getDatasetCount(); i++) {
                CategoryDataset cpds = cp.getDataset(i);
                for (int rowIndex = 0; rowIndex < cpds.getRowCount(); rowIndex++) {
                    for (int columnIndex = 0; columnIndex < cpds.getColumnCount(); columnIndex++) {
                        Number value = cpds.getValue(rowIndex, columnIndex);
                        writer.write(cpds.getRowKey(rowIndex).toString());
                        writer.write("\t");
                        writer.write(cpds.getColumnKey(columnIndex).toString());
                        writer.write("\t");
                        writer.write(Integer.toString(rowIndex));
                        writer.write("\t");
                        writer.write(Integer.toString(columnIndex));
                        writer.write("\t");
                        writer.write(value.toString());
                        writer.newLine();
                    }
                }
            }

        }
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.openvpms.web.resource.i18n.format.NumberFormatter.java

/**
 * Formats a currency amount.//ww w.j a  va 2  s .  co m
 * <p/>
 * When using {@link Messages}, this should be used to format amounts instead of using currency MessageFormats.
 * This is due to the fact that {@link Messages} uses the browser's locale to format messages, which may have a
 * different currency symbol to that of the practice.
 *
 * @param amount the amount. May be {@code null}
 * @return the formatted amount, or {@code null} if {@code value} is {@code null}
 */
public static String formatCurrency(Number amount) {
    String result;
    if (amount != null) {
        try {
            result = getCurrencyFormat().format(amount);
        } catch (IllegalArgumentException exception) {
            result = amount.toString();
        }
    } else {
        result = null;
    }
    return result;
}

From source file:org.openvpms.web.resource.i18n.format.NumberFormatter.java

/**
 * Format a number.//from   w w w.  j  a v  a  2 s.  com
 *
 * @param value  the number to format. May be {@code null}
 * @param format the formatter
 * @return the formatted number, or {@code null} if {@code value} is {@code null}
 */
public static String format(Number value, NumberFormat format) {
    String result;
    if (value != null) {
        try {
            result = format.format(value);
        } catch (IllegalArgumentException exception) {
            result = value.toString();
        }
    } else {
        result = null;
    }
    return result;
}

From source file:org.apache.hadoop.hbase.util.JSONBean.java

private static void writeObject(final JsonGenerator jg, final boolean description, Object value)
        throws IOException {
    if (value == null) {
        jg.writeNull();/* ww w .  ja  v  a2  s  .  co  m*/
    } else {
        Class<?> c = value.getClass();
        if (c.isArray()) {
            jg.writeStartArray();
            int len = Array.getLength(value);
            for (int j = 0; j < len; j++) {
                Object item = Array.get(value, j);
                writeObject(jg, description, item);
            }
            jg.writeEndArray();
        } else if (value instanceof Number) {
            Number n = (Number) value;
            jg.writeNumber(n.toString());
        } else if (value instanceof Boolean) {
            Boolean b = (Boolean) value;
            jg.writeBoolean(b);
        } else if (value instanceof CompositeData) {
            CompositeData cds = (CompositeData) value;
            CompositeType comp = cds.getCompositeType();
            Set<String> keys = comp.keySet();
            jg.writeStartObject();
            for (String key : keys) {
                writeAttribute(jg, key, null, cds.get(key));
            }
            jg.writeEndObject();
        } else if (value instanceof TabularData) {
            TabularData tds = (TabularData) value;
            jg.writeStartArray();
            for (Object entry : tds.values()) {
                writeObject(jg, description, entry);
            }
            jg.writeEndArray();
        } else {
            jg.writeString(value.toString());
        }
    }
}

From source file:eu.crisis_economics.configuration.FromFileConfigurationContext.java

private static String scanForNamesAndReplace(String expression, String name, Number value) {
    int cursor = 0;
    String replacement = value.toString(), result = expression;
    int replacementCursorDelta = replacement.length() - name.length();
    while (true) {
        cursor = result.indexOf(name, cursor);
        if (cursor == -1)
            break;
        int nextCharAfterWordIndex = cursor + name.length();
        if (nextCharAfterWordIndex == result.length()) {
            result = result.substring(0, cursor) + replacement;
            break;
        }//from  ww  w  . jav a 2s  .c o m
        Character nextCharAfterWord = result.charAt(nextCharAfterWordIndex);
        if (Character.isLetter(nextCharAfterWord) || nextCharAfterWord == '_')
            ++cursor;
        else {
            result = result.substring(0, cursor) + replacement + result.substring(nextCharAfterWordIndex);
            cursor += replacementCursorDelta;
        }
    }
    return result;
}

From source file:org.nuxeo.ecm.core.search.api.client.querymodel.descriptor.QueryModelDescriptor.java

protected static void appendNumberArray(StringBuilder queryBuilder, Number[] numbers) {
    queryBuilder.append('(');
    List<String> params = new ArrayList<String>(numbers.length);
    for (Number param : numbers) {
        params.add(param.toString());
    }/* w w  w.  java  2 s  .c om*/
    queryBuilder.append(StringUtils.join(params, ", "));
    queryBuilder.append(')');
}

From source file:com.meterware.httpunit.HttpUnitUtils.java

/**
 * Returns a string representation of a number, trimming off any trailing decimal zeros.
 *//*from   w  ww  .  j  a  va 2  s  . c  o  m*/
static String trimmedValue(Number number) {
    String rawNumber = number.toString();
    if (rawNumber.indexOf('.') == -1)
        return rawNumber;

    int index = rawNumber.length();
    while (rawNumber.charAt(index - 1) == '0')
        index--;
    if (rawNumber.charAt(index - 1) == '.')
        index--;
    return rawNumber.substring(0, index);
}

From source file:com.kcs.core.utilities.Utility.java

public static String getXmlString(Number number) {
    return (Utility.isNull(number) ? StringUtil.BLANK : number.toString());
}

From source file:org.vulpe.view.struts.tags.StrutsFunctions.java

/**
 *
 * @param pageContext/*from   ww  w . jav a 2s.  com*/
 * @param property
 * @param contentType
 * @param contentDisposition
 * @return
 * @throws JspException
 */
public static String linkProperty(final PageContext pageContext, final String property,
        final String contentType, final String contentDisposition) throws JspException {
    String baseName = "entity.";
    final VulpeBaseDetailConfig detailConfig = (VulpeBaseDetailConfig) eval(pageContext, "${targetConfig}");
    if (detailConfig != null) {
        final Number index = (Number) eval(pageContext,
                "${".concat(detailConfig.getBaseName()).concat("_status.index}"));
        baseName = eval(pageContext, "${targetConfigPropertyName}").toString().concat("[")
                .concat(index.toString()).concat("].");
    }

    final String key = (property.contains(baseName)) ? property : baseName.concat(property);

    final Object value = getProperty(pageContext, property);
    if (VulpeValidationUtil.isNotEmpty(value)) {
        saveInSession(key, value, false);
    }

    return linkKey(key, contentType, contentDisposition);
}