Java Fraction Format formatDouble(double value, int precision)

Here you can find the source of formatDouble(double value, int precision)

Description

Returns a formatted Double value given a specific DecimalFormat
If more than 4 integer, then we display the value in scientific notation

License

Open Source License

Parameter

Parameter Description
value a parameter
precision a parameter

Return

a double value formatted as a String

Declaration

public static String formatDouble(double value, int precision) 

Method Source Code


//package com.java2s;
/*//from  w ww . j a  va  2 s  . com
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.text.DecimalFormat;

public class Main {
    /**
     * Returns a formatted Double value given a specific DecimalFormat<br>
     * If more than 4 integer, then we display the value in scientific notation
     * @param value
     * @param precision
     * @return a double value formatted as a String
     */
    public static String formatDouble(double value, int precision) {
        String result;
        if (((int) value) > 9999 || ((int) value) < -9999) {
            result = new DecimalFormat("0.######E0").format(value);
        } else
            result = String.valueOf(roundDouble(value, precision));
        return result == null ? "-" : result;
    }

    /**
     * Method that rounds a value to the n precision decimals
     * @param value
     * @param precision
     * @return a double value rounded to n precision
     */
    public static double roundDouble(double value, int precision) {
        int rounder = (int) Math.pow(10, precision);
        return (double) Math.round(value * rounder) / rounder;
    }
}

Related

  1. formatDouble(double orig)
  2. formatDouble(Double someDouble)
  3. formatDouble(Double v)
  4. formatDouble(double value)
  5. formatDouble(double value)
  6. FormatDouble(final double dblValue, final int iNumLeft, final int iNumRight, final double dblMultiplier)
  7. formatDouble(Object obj)
  8. formatDouble(Object value)
  9. formatDoubleAmount(double amount)