Java Double Number to String doubleToScientificString(double number, int fractionDigits)

Here you can find the source of doubleToScientificString(double number, int fractionDigits)

Description

Returns the string representation of the given double value in normalized scientific notation.

License

Open Source License

Parameter

Parameter Description
number the double to convert
fractionDigits the number of digits in the fraction part, e.g., 4 in "1.2345e+05".

Return

the string representation of the double in scientific notation

Declaration

public static String doubleToScientificString(double number,
        int fractionDigits) 

Method Source Code

//package com.java2s;
/*/*  ww w .  ja va 2 s.c o  m*/
 * Copyright 1999-2002 Carnegie Mellon University.  
 * Portions Copyright 2002 Sun Microsystems, Inc.  
 * Portions Copyright 2002 Mitsubishi Electric Research Laboratories.
 * All Rights Reserved.  Use is subject to license terms.
 * 
 * See the file "license.terms" for information on usage and
 * redistribution of this file, and for a DISCLAIMER OF ALL 
 * WARRANTIES.
 *
 */

import java.text.DecimalFormat;

public class Main {
    /**
     * Returns the string representation of the given double value in normalized scientific notation. The
     * <code>fractionDigits</code> argument gives the number of decimal digits in the fraction portion. For example, if
     * <code>fractionDigits</code> is 4, then the 123450 will be "1.2345e+05". There will always be two digits in the
     * exponent portion, and a plus or minus sign before the exponent.
     *
     * @param number         the double to convert
     * @param fractionDigits the number of digits in the fraction part, e.g., 4 in "1.2345e+05".
     * @return the string representation of the double in scientific notation
     */
    public static String doubleToScientificString(double number,
            int fractionDigits) {
        DecimalFormat format = new DecimalFormat();

        StringBuilder formatter = new StringBuilder(5 + fractionDigits)
                .append("0.");
        for (int i = 0; i < fractionDigits; i++) {
            formatter.append('0');
        }
        formatter.append("E00");

        format.applyPattern(formatter.toString());
        String formatted = format.format(number);

        int index = formatted.indexOf('E');
        if (formatted.charAt(index + 1) != '-') {
            return formatted.substring(0, index + 1) + '+'
                    + formatted.substring(index + 1);
        } else {
            return formatted;
        }
    }
}

Related

  1. doublesToStrings(final double... numbers)
  2. doubleToAtLeastString(double d, int length)
  3. doubleToCoreString(double number)
  4. doubleToDollarString(double val)
  5. doubleToFixedString(double d, int length)
  6. doubleToStr(double d)
  7. doubleToStr(double origin, int decimals)
  8. doubleToStr1(double d)
  9. doubleToStrFormatado(Double valor)