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:NumberUtils.java

/**
 * Converts the given number to a <code>java.math.BigInteger</code>.
 *
 * @param number//  w  w  w.ja  va2s  . c  o  m
 * @return java.math.BigInteger
 * @throws IllegalArgumentException The given number is 'not a number' or infinite.
 */
public static BigInteger toBigInteger(Number number) throws IllegalArgumentException {
    if (number == null || number instanceof BigInteger)
        return (BigInteger) number;
    if (number instanceof BigDecimal)
        return ((BigDecimal) number).toBigInteger();
    if (isDoubleCompatible(number)) {
        if (isNaN(number) || isInfinite(number))
            throw new IllegalArgumentException("Argument must not be NaN or infinite.");
        return new BigDecimal(number.toString()).toBigInteger();
    } // => isLongCompatible(number) or unknown Number type
    return BigInteger.valueOf(number.longValue());
}

From source file:NumberUtils.java

/**
 * Converts the given number to a <code>java.math.BigDecimal</code>.
 *
 * @param number/*from w  w  w.  j a  v a2s.co m*/
 * @return java.math.BigDecimal
 * @throws IllegalArgumentException The given number is 'not a number' or infinite.
 */
public static BigDecimal toBigDecimal(Number number) throws IllegalArgumentException {
    if (number == null || number instanceof BigDecimal)
        return (BigDecimal) number;
    if (number instanceof BigInteger)
        return new BigDecimal((BigInteger) number);
    if (isDoubleCompatible(number)) {
        if (isNaN(number) || isInfinite(number))
            throw new IllegalArgumentException("Argument must not be NaN or infinite.");
        return new BigDecimal(number.toString());
    }
    if (isLongCompatible(number))
        return BigDecimal.valueOf(number.longValue());
    // => unknown Number type
    return new BigDecimal(String.valueOf(number.doubleValue()));
}

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

/**
 * ?? ??? 0.0,0.5,1.0,1.5,2.0,2.5....//from w  ww.  j a v a 2s . c o m
 * 
 * <p>
 *  
 * </p>
 *
 * @param value
 *            
 * @return 0.0,0.5,1.0,1.5,2.0,2.5.......
 */
public static String toPointFive(Number value) {
    if (Validator.isNullOrEmpty(value)) {
        throw new NullPointerException("value can't be null/empty!");
    }
    long avgRankLong = Math.round(Double.parseDouble(value.toString()) * 2);

    BigDecimal avgBigDecimal = BigDecimal.valueOf((double) (avgRankLong) / 2);
    return setScale(avgBigDecimal, 1).toString();
}

From source file:playground.dgrether.analysis.charts.utils.DgChartWriter.java

public static void writeChartDataToFile(String filename, JFreeChart chart) {
    filename += ".txt";
    try {//from  ww w  . j a va2 s .co 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();
            //write the header
            writer.write("#");
            for (int i = 0; i < xy.getDatasetCount(); i++) {
                XYDataset xyds = xy.getDataset(i);
                int seriesIndex = 0;
                int maxItems = 0;
                int seriesCount = xyds.getSeriesCount();
                while (seriesIndex < seriesCount) {
                    writer.write("Series " + xyds.getSeriesKey(seriesIndex).toString());
                    if (seriesIndex < seriesCount - 1) {
                        writer.write("\t \t");
                    }
                    if (xyds.getItemCount(seriesIndex) > maxItems) {
                        maxItems = xyds.getItemCount(seriesIndex);
                    }
                    seriesIndex++;
                }
                writer.newLine();

                //write the data
                Number xValue, yValue = null;
                for (int itemsIndex = 0; itemsIndex < maxItems; itemsIndex++) {
                    for (int seriesIdx = 0; seriesIdx < seriesCount; seriesIdx++) {
                        if (seriesIdx < xyds.getSeriesCount() && itemsIndex < xyds.getItemCount(seriesIdx)) {
                            xValue = xyds.getX(seriesIdx, itemsIndex);
                            yValue = xyds.getY(seriesIdx, itemsIndex);
                            if (xValue != null && yValue != null) {
                                writer.write(xValue.toString());
                                writer.write("\t");
                                writer.write(yValue.toString());
                                if (seriesIdx < seriesCount - 1) {
                                    writer.write("\t");
                                }
                            }
                        }
                    }
                    writer.newLine();
                }
            }
        } catch (ClassCastException e) { //else instanceof CategoryPlot
            log.info("Due to a caught class cast exception, it should be a 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();
        log.info("Chart data written to: " + filename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:MathUtils.java

/**
 *  Numbers will be equals if enough decimals are equals, without thinking about approximations. This is absolutely not a pure mathematic Equality.
 * <p>/*from   w ww  .  ja  v a  2 s . c o m*/
 * approximativelyEquals(1.2352, 1.2357, 3) returns true because there is no rounding at the 3th decimal
 * </p>
 *
 * @param n1 first numbre
 * @param n2 second number
 * @param decimalPrecision
 * @return true if n1 is approximatively equal to n2
 */
public static boolean approximativelyEquals(Number n1, Number n2, int decimalPrecision) {

    if (n1.toString().equals(n2.toString())) {
        return true;
    }

    String s1 = n1.toString();
    String s2 = n2.toString();

    s1 = StringUtils.removeTrailingCharacters(s1, '0');
    s2 = StringUtils.removeTrailingCharacters(s2, '0');

    if (!s1.contains(".") && !s2.contains(".")) {
        return s1.equals(s2);
    }

    int seriousNumber;
    if (s1.contains(".")) {
        seriousNumber = s1.indexOf('.');
    } else {//s2.contains(".")
        seriousNumber = s2.indexOf('.');
    }

    /* checking before */
    if (s1.substring(0, seriousNumber).equals(s2.substring(0, seriousNumber))) {

        s1 = s1.substring(seriousNumber);
        s1 = StringUtils.removeCharacter(s1, '.');
        s2 = s2.substring(seriousNumber);
        s2 = StringUtils.removeCharacter(s2, '.');

        /* truncation */
        String t1 = StringUtils.truncate(s1, decimalPrecision);
        String t2 = StringUtils.truncate(s2, decimalPrecision);
        t1 = StringUtils.removeTrailingCharacters(t1, '0');
        t2 = StringUtils.removeTrailingCharacters(t2, '0');
        return t1.equals(t2);

    } else {
        return false;
    }
}

From source file:jp.co.ctc_g.jse.core.validation.util.Validators.java

/**
 * BigDecimal?????/* w  w  w.j  a  va  2  s  .c  o m*/
 * @param suspect Number
 * @return 
 */
public static BigDecimal toBigDecimal(Number suspect) {
    if (suspect instanceof BigDecimal) {
        return (BigDecimal) suspect;
    } else {
        return new BigDecimal(suspect.toString());
    }
}

From source file:MathUtils.java

/**
 * <p>//from  ww w .j  a  va  2  s.c o m
 * Returns a visual approximation of a number, keeping only a specified decimals. <br/>
 * For exemple : <br/>
 *    &nbsp; approximate(12.2578887 , 2) will return 12.25 <br/>
 *    &nbsp; approximate(12.25 , 0) will return 12 <br/>
 *    &nbsp; approximate(12.00 , 3) will return 12 <br/>
 *    &nbsp; approximate(19.5 , 0) will return 20 <br/>
 *</p>
 * <p>The last exemple emphasis the fact that it's made for showing convenient numbers for no mathematical public. If the number was</p>
 * <p>Note that Math.round(19.5) returns 20, not 19. This function will act the same way.</p>
 * @param n
 * @param precision
 * @return
 */
public static String approximate(Number n, int precision) {

    if (n instanceof Integer) {
        return n.toString();
    }

    String s = n.toString();

    if (!s.contains(".")) {
        return s;
    }

    String serious = s.substring(0, s.indexOf('.'));

    s = s.substring(s.indexOf('.') + 1);
    s = StringUtils.removeTrailingCharacters(s, '0');

    if (s.length() == 0) {
        return serious;
    }

    // We'll comments results based on approximate(12.63645, 3) and approximate(12.63545, 0)
    String decimals = "";

    if (s.length() > precision) {

        decimals = StringUtils.truncate(s, precision + 1);
        //decimal is now "636" or "6"

        Float after = new Float(decimals);
        //after is 636 or 6, as Float objects
        after = after / 10;
        //after is 63.6 or .6, as Float objects
        Integer round = Math.round(after);
        //round is 64 or 1
        decimals = round.toString();
        decimals = StringUtils.removeTrailingCharacters(decimals, '0');

    } else {

        decimals = StringUtils.truncate(s, precision);
        decimals = StringUtils.removeTrailingCharacters(decimals, '0');

    }

    if (decimals.length() > 0 && precision > 0) {
        return serious + "." + decimals;
    } else {
        //if we must round the serious string
        if (decimals.length() > 0 && precision == 0) {
            assert decimals.length() == 1 : "problem here !";
            if (decimals.length() != 1) {
                throw new IllegalStateException(
                        "Error in the algorithm for MathUtilisties.approximate(" + n + ", " + precision + ")");
            }
            Integer finalValue = new Integer(decimals);
            if (finalValue > 0) {
                Integer si = new Integer(serious);
                si += 1;
                return si.toString();
            } else {
                return serious;
            }
        } else {
            return serious;
        }
    }
}

From source file:net.sf.json.JSONUtils.java

/**
 * Produce a string from a Number.//w w w .  j  a  v  a2  s  . com
 *
 * @param n A Number
 * @return A String.
 * @throws JSONException If n is a non-finite number.
 */
public static String numberToString(Number n) {
    if (n == null) {
        throw new JSONException("Null pointer");
    }

    JSONUtils.testValidity(n);

    // Shave off trailing zeros and decimal point, if possible.
    String s = n.toString();

    if ((s.indexOf('.') > 0) && (s.indexOf('e') < 0) && (s.indexOf('E') < 0)) {
        while (s.endsWith("0")) {
            s = s.substring(0, s.length() - 1);
        }

        if (s.endsWith(".")) {
            s = s.substring(0, s.length() - 1);
        }
    }

    return s;
}

From source file:org.eclipse.dawnsci.doe.DOEUtils.java

/**
 * Recursive method which expands out all the simulations into
 * a 1D list from the ranges specified. This reads the annotation
 * weightings to construct the loops based on parameter weighting.
 * //from ww w .j av  a 2s .c  o m
 * For instance temperature might be in an outer loop to process all
 * experiments at a given temperature together.
 * 
 * @param clone
 * @param orderedFields
 * @param index
 * @param ret
 * @throws Exception
 */
protected static void expand(Serializable clone, final List<FieldContainer> orderedFields, final int index,
        final List<Object> ret) throws Exception {

    if (index >= orderedFields.size()) {
        // NOTE: You must implement hashCode and equals 
        // on all beans. These are used to avoid adding
        // repeats.
        if (!ret.contains(clone))
            ret.add(clone);
        return;
    }

    final FieldContainer field = orderedFields.get(index);

    final Object originalObject = field.getOriginalObject();
    final String stringValue = (String) getBeanValue(originalObject, field.getName());
    if (stringValue == null) {
        expand(clone, orderedFields, index + 1, ret);
        return;
    }

    final String range = stringValue.toString();
    final List<? extends Number> vals = DOEUtils.expand(range, field.getAnnotation().type());
    for (Number value : vals) {
        clone = deepClone(clone);
        setBeanValue(clone, field, value.toString(), field.getListIndex());
        expand(clone, orderedFields, index + 1, ret);
    }

}

From source file:com.xwtec.xwserver.util.json.util.JSONUtils.java

/**
 * Transforms a Number into a valid javascript number.<br>
 * Float gets promoted to Double.<br>
 * Byte and Short get promoted to Integer.<br>
 * Long gets downgraded to Integer if possible.<br>
 *///ww w  .  j  av a  2 s  . com
public static Number transformNumber(Number input) {
    if (input instanceof Float) {
        return new Double(input.toString());
    } else if (input instanceof Short) {
        return new Integer(input.intValue());
    } else if (input instanceof Byte) {
        return new Integer(input.intValue());
    } else if (input instanceof Long) {
        Long max = new Long(Integer.MAX_VALUE);
        if (input.longValue() <= max.longValue() && input.longValue() >= Integer.MIN_VALUE) {
            return new Integer(input.intValue());
        }
    }

    return input;
}