Java Number to String numberToString(Number number)

Here you can find the source of numberToString(Number number)

Description

Produce a string from a Number.

License

Apache License

Parameter

Parameter Description
number A Number

Exception

Parameter Description
JSONException If n is a non-finite number.

Return

A String.

Declaration

protected static String numberToString(Number number) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from w  ww.ja v  a2s  .  co m*/
    * Produce a string from a Number.
    *
    * @param number
    * A Number
    * @return A String.
    * @throws JSONException
    * If n is a non-finite number.
    */
    protected static String numberToString(Number number) {
        if (number == null) {
            return "null";
        }
        if (!testValidity(number)) {
            throw new RuntimeException("Can't convert number: " + number);
        }

        // Shave off trailing zeros and decimal point, if possible.

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

    /**
     * Throw an exception if the object is a NaN or infinite number.
     *
     * @param o
     * The object to test.
     * @throws JSONException
     * If o is a non-finite number.
     */
    protected static boolean testValidity(Object o) {
        if (o != null) {
            if (o instanceof Double) {
                if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
                    return false;
                }
            } else if (o instanceof Float) {
                if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}

Related

  1. numberToString(double num, int digits)
  2. numberToString(int gmNumber)
  3. numberToString(int number, int length, String type, int location)
  4. numberToString(Object instance)
  5. numberToString(Object num)
  6. numberToStringFlushLeft(long number, int width)