Example usage for java.text DecimalFormat format

List of usage examples for java.text DecimalFormat format

Introduction

In this page you can find the example usage for java.text DecimalFormat format.

Prototype

public final String format(double number) 

Source Link

Document

Specialization of format.

Usage

From source file:com.fengduo.spark.commons.file.FileUtils.java

private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
    if (fileSize == 0)
        return "0";

    if (fileSize / unit >= 1) {
        double value = fileSize / (double) unit;
        DecimalFormat df = new DecimalFormat("######.##" + unitName);
        return df.format(value);
    }/*from   w ww . java2  s  .co  m*/
    return null;
}

From source file:Currently.java

/**
 * Ignores any internal date format, and tries to show a complete
 * date/timp stamp in extended ISO 8601 format. UTC time (Zulu time)
 * or a local timezone will be used.<p>
 *
 * <table border=1>//  ww w . j a  va 2 s . c o  m
 * <tr><th>zone</th><th>format</th><th>fraction</td><th>example</th></tr>
 * <tr><td>local</td><td>basic</td><td>integral</td><td>20020523T140427-0500</td></tr>
 * <tr><td>UTC</td><td>basic</td><td>integral</td><td>20020523190427Z</td></tr>
 * <tr><td>local</td><td>extd.</td><td>integral</td><td>2002-05-23T14:04:27-05:00</td></tr>
 * <tr><td>UTC</td><td>extd.</td><td>integral</td><td>2002-05-23T19:04:27Z</td></tr>
 * <tr><td>local</td><td>basic</td><td>millis</td><td>20020523T140427.166-0500</td></tr>
 * <tr><td>UTC</td><td>basic</td><td>millis</td><td>20020523190427.166Z</td></tr>
 * <tr><td>local</td><td>extd.</td><td>millis</td><td>2002-05-23T14:04:27.166-05:00</td></tr>
 * <tr><td>UTC</td><td>extd.</td><td>millis</td><td>2002-05-23T19:04:27.166Z</td></tr>
 * </table><p>
 *
 * @param zuluTime returns a UTC formatted stamp, if true. Otherwise
 * the time will be formatted according to the local zone. Local time
 * should be prefixed with the 'T'.
 * @param extendedFormat will use the extended ISO 8601 format which
 * separates the different timestamp items. If false, the basic
 * format will be used. In UTC and basic format, the 'T' separator
 * will be omitted.
 * @param withMillis will put the millisecond extension into the timestamp.
 * If false, the time will be without millisecond fraction. The separator
 * is taken from {@link java.text.DecimalFormatSymbols#getMinusSign()},
 * which usually is a period or a comma.
 * @param now is a time stamp as Date.
 * @return an ISO 8601 formatted date and time representation for
 * the given point in time.
 */
public static String iso8601(boolean zuluTime, boolean extendedFormat, boolean withMillis, Date now) {
    Calendar c = Calendar.getInstance(zuluTime ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault());
    c.setTime(now);

    // set up formattting options
    DecimalFormat nf2 = new DecimalFormat("##00");
    DecimalFormat nf3 = new DecimalFormat("###000");
    DecimalFormat nf4 = new DecimalFormat("####0000");
    DecimalFormatSymbols dfs = nf2.getDecimalFormatSymbols();

    // allocate result string buffer
    int size = extendedFormat ? (zuluTime ? 25 : 30) : (zuluTime ? 21 : 25);
    if (!withMillis) {
        size -= 4;
    }
    StringBuffer result = new StringBuffer(size);

    result.append(nf4.format(c.get(Calendar.YEAR)));
    if (extendedFormat) {
        result.append('-'); // position 5
    }
    result.append(nf2.format(c.get(Calendar.MONTH) + 1));
    if (extendedFormat) {
        result.append('-'); // position 8
    }
    result.append(nf2.format(c.get(Calendar.DAY_OF_MONTH)));
    // generating UTC in basic format may leave out the 'T' separator
    if (extendedFormat || !zuluTime) {
        result.append('T'); // position 11
    }
    result.append(nf2.format(c.get(Calendar.HOUR_OF_DAY)));
    if (extendedFormat) {
        result.append(':'); // position 14
    }
    result.append(nf2.format(c.get(Calendar.MINUTE)));
    if (extendedFormat) {
        result.append(':'); // position 17
    }
    result.append(nf2.format(c.get(Calendar.SECOND)));

    if (withMillis) {
        // Though there is no explicit spec which allows a complete
        // timestamp with milliseconds, it is implied through two
        // levels, sigh. 5.3.4.2 allows decimal fractions with
        // time-only stamps that have a timezone. The intro of 5.4.2
        // allows 5.3.1.3.
        result.append(dfs.getDecimalSeparator()); // position 20
        result.append(nf3.format(c.get(Calendar.MILLISECOND)));
    }

    if (zuluTime) {
        // this is easy
        result.append('Z');
    } else {
        // time zone calculations
        int zone_offset = c.get(Calendar.ZONE_OFFSET) / 1000;
        int save_offset = c.get(Calendar.DST_OFFSET) / 1000;
        int diff = (zone_offset + save_offset) / 60;
        result.append(diff < 0 ? dfs.getMinusSign() : '+'); // position 24

        if (diff < 0) {
            diff = Math.abs(diff);
        }
        result.append(nf2.format(diff / 60));
        if (extendedFormat) {
            result.append(':');
        }
        result.append(nf2.format(diff % 60));
    }

    return result.toString();
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentOrderProcessAction.java

private static String roundTo2DecimalPlaces(double value) {

    DecimalFormat df = new DecimalFormat("0.000");
    String doublevalue = df.format(value);

    System.out.println("------kfkdjd" + doublevalue + "--------");
    return doublevalue;
}

From source file:com.yyl.common.utils.excel.ExcelTools.java

/**
 *    ?cell//from   w  w w  .j  a v a2 s .c o m
 * @param cell
 * @return
 */
private static String getCellValue(HSSFCell cell) {
    if (cell == null) {
        return "";
    }
    switch (cell.getCellType()) {
    case HSSFCell.CELL_TYPE_NUMERIC: {
        DecimalFormat df = new DecimalFormat("0");
        return df.format(cell.getNumericCellValue());
    }
    default:
        return String.valueOf(cell.getStringCellValue());
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * ? format "#,###"//from  w  ww.j  av  a  2  s . com
 * 
 * @param number
 * @return
 */
public static String getDisplayNumber(String number) {
    if (StringUtils.isEmpty(number) || !StringUtils.isNumeric(number)) {
        return "0";
    }
    Double dNum = Double.valueOf(number);
    DecimalFormat fm = new DecimalFormat("#,###");
    return fm.format(dNum);
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * //from ww  w .j  a v  a 2s. c o m
 * Format {@link String} like a number with given decimals
 * 
 * @param locale {@link Locale}
 * @param stringToFormat {@link String} to format
 * @param minimalNumberOfDecimals minimal amount of decimals. Can be any number, also negative as the used DecimalFormatter 
 * @param maximumNumberOfDecimals maximum amount of decimals. Can be any number, also negative as the used DecimalFormatter 
 * @return a {@link String} formatted as a number with given decimals assuming the receiver is a float string read from XML
 */
public static String formatNumberWithDecimals(Locale locale, String stringToFormat, int minimalNumberOfDecimals,
        int maximumNumberOfDecimals) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    setupFormatter(formatter, locale, minimalNumberOfDecimals, maximumNumberOfDecimals);

    result = formatter.format(Double.parseDouble(stringToFormat));

    return result;
}

From source file:br.com.itfox.utils.Utils.java

public static String formatDecimal(BigDecimal val) {
    String s = "";
    try {//from   ww w . j  av  a  2s  .  co m
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale("en", "EN"));
        df.setMaximumFractionDigits(Preferences.MAXIMUM_FRACTION_DIGITS);
        df.setMinimumFractionDigits(Preferences.MINIMUM_FRACTION_DIGITS);
        df.setMinimumIntegerDigits(Preferences.MIMIMUM_INTEGER_DIGITS);
        df.setRoundingMode(Preferences.ROUNDING_MODE);
        s = String.valueOf(df.format(val));
    } catch (Exception ex) {
        br.com.itfox.utils.Logger.getLogger(ex, Utils.class.getName() + "***" + val + "***", ex.getMessage());
    }
    return s;

}

From source file:Main.java

/**
 * Get the file size in a human-readable string.
 * //  w  w  w .  ja va 2 s.c o m
 * @param size
 * @return
 * 
 * @author paulburke
 */
public static String getReadableFileSize(int size) {
    final int BYTES_IN_KILOBYTES = 1024;
    final DecimalFormat dec = new DecimalFormat("###.#");
    final String KILOBYTES = " KB";
    final String MEGABYTES = " MB";
    final String GIGABYTES = " GB";
    float fileSize = 0;
    String suffix = KILOBYTES;

    if (size > BYTES_IN_KILOBYTES) {
        fileSize = size / BYTES_IN_KILOBYTES;
        if (fileSize > BYTES_IN_KILOBYTES) {
            fileSize = fileSize / BYTES_IN_KILOBYTES;
            if (fileSize > BYTES_IN_KILOBYTES) {
                fileSize = fileSize / BYTES_IN_KILOBYTES;
                suffix = GIGABYTES;
            } else {
                suffix = MEGABYTES;
            }
        }
    }
    return String.valueOf(dec.format(fileSize) + suffix);
}

From source file:com.itude.mobile.android.util.StringUtil.java

public static String formatNumberWithOriginalNumberOfDecimals(String stringToFormat, Locale locale) {

    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }/*www  .  ja  va 2  s  .com*/

    String result = null;

    DecimalFormat formatter = new DecimalFormat("#################.####################",
            new DecimalFormatSymbols(locale));

    try {
        result = formatter.format(Double.parseDouble(stringToFormat));
    } catch (Exception e) {
        MBLog.w(TAG, "Could not format string " + stringToFormat
                + " as number with original number of decimals (StringUtilities)", e);

        return null;
    }

    return result;
}

From source file:edu.iu.daal_pca.Service.java

public static void printMatrix(double[] matrix, int nCols, int nRows, String header) {
    System.out.println(header);//from  w  ww  . j a va 2 s.co  m
    DecimalFormat numberFormat = new DecimalFormat("##0.00");
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            System.out.print(numberFormat.format(matrix[i * nCols + j]) + "\t\t");
        }
        System.out.println();
    }
}