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.sunchenbin.store.feilong.core.text.NumberFormatUtil.java

/**
 *  {@link Number}  {@link RoundingMode} numberPattern?.
 *
 * @param value/*  ww w .j a  v  a2s.c o  m*/
 *            the value
 * @param numberPattern
 *            the pattern {@link NumberPattern}
 * @param roundingMode
 *            ?{@link RoundingMode}
 * @return  null
 * @see NumberPattern
 * @see DecimalFormat
 * @see <a href="../util/NumberUtil.html#RoundingMode">JAVA 8??</a>
 */
public static String format(Number value, String numberPattern, RoundingMode roundingMode) {
    if (null == value) {
        throw new NullPointerException("the value is null or empty!");
    }

    if (null == numberPattern) {
        throw new NullPointerException("the numberPattern is null or empty!");
    }
    try {
        // applyPattern(pattern, false)
        DecimalFormat decimalFormat = new DecimalFormat(numberPattern);

        // ? RoundingMode.HALF_EVEN
        // ?,?.?,?.??,?,??.???1?,???.
        // 1.15>1.2 1.25>1.2
        if (null != roundingMode) {
            decimalFormat.setRoundingMode(roundingMode);
        }
        String format = decimalFormat.format(value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("value:[{}], pattern:[{}],return:[{}],decimalFormat.toLocalizedPattern():[{}]", value,
                    numberPattern, format, decimalFormat.toLocalizedPattern()//?? Format ????. 
            );
        }
        return format;
    } catch (Exception e) {
        Object[] objects = { e.getMessage(), value, numberPattern };
        LOGGER.error("{},value:[{}],pattern:[{}]", objects);
        LOGGER.error(e.getClass().getName(), e);
    }
    return StringUtils.EMPTY;
}

From source file:com.sfs.Formatter.java

/**
 * File size./*ww  w  .  jav a 2 s .  com*/
 *
 * @param bytes the bytes
 *
 * @return the string
 */
public static String fileSize(final long bytes) {

    String filesize = "";

    final int maxBytes = 1024;
    final double dbMaxBytes = 1024.0;

    if (bytes < maxBytes) {
        DecimalFormat formatter = new DecimalFormat("#,##0");
        filesize = formatter.format((double) bytes) + " bytes";
    } else if (bytes < maxBytes * maxBytes) {
        DecimalFormat formatter = new DecimalFormat("#,##0.0");
        filesize = formatter.format((double) bytes / dbMaxBytes) + " kb";
    } else if (bytes < maxBytes * maxBytes * maxBytes) {
        DecimalFormat formatter = new DecimalFormat("#,##0.0");
        filesize = formatter.format((double) bytes / (dbMaxBytes * dbMaxBytes)) + " mb";
    } else {
        DecimalFormat formatter = new DecimalFormat("#,##0.0");
        filesize = formatter.format((double) bytes / (dbMaxBytes * dbMaxBytes * dbMaxBytes)) + " gb";
    }
    return filesize;
}

From source file:juicebox.tools.utils.juicer.apa.APAPlotter.java

/**
 * Plot number value axis for color scale bar.
 *
 * @param g2      graphics2D object//from w w w .  ja v  a  2s.c o  m
 * @param heatMap object
 */
private static void plotColorScaleValues(Graphics2D g2, HeatChart heatMap) {
    // size, increment calculations
    double valIncrement = Math.max(heatMap.getDataRange() / ((double) numDivisions), epsilon);
    double depthIncrement = ((double) (fullHeight - 2 * colorScaleVerticalMargin)) / ((double) numDivisions);
    int verticalDepth = fullHeight - colorScaleVerticalMargin;
    int csBarRightEdgeX = fullWidth - colorScaleHorizontalMargin - extraWidthBuffer;

    // formatting
    g2.setFont(heatMap.getAxisValuesFont());
    DecimalFormat df = new DecimalFormat("0.#");

    // draw each tick mark and its value
    for (double i = heatMap.getLowValue(); i <= heatMap
            .getHighValue(); i += valIncrement, verticalDepth -= depthIncrement) {

        if (i > heatMap.getHighValue() - epsilon)
            verticalDepth = colorScaleVerticalMargin;
        g2.drawString(df.format(i), csBarRightEdgeX + 5, verticalDepth); // value
        g2.drawLine(csBarRightEdgeX - 5, verticalDepth, csBarRightEdgeX, verticalDepth); // tick mark
    }
}

From source file:Main.java

public static String safeDoubleToCurrency(Double val) {
    BigDecimal value = BigDecimal.valueOf(val);
    DecimalFormat kursIndonesia = (DecimalFormat) DecimalFormat.getCurrencyInstance();
    DecimalFormatSymbols formatRp = new DecimalFormatSymbols();

    formatRp.setCurrencySymbol("");
    formatRp.setMonetaryDecimalSeparator('.');
    formatRp.setGroupingSeparator(',');

    kursIndonesia.setDecimalFormatSymbols(formatRp);
    kursIndonesia.setParseBigDecimal(true);
    if (val < 1)
        kursIndonesia.setMaximumFractionDigits(8);
    else if (val < 10)
        kursIndonesia.setMaximumFractionDigits(6);
    else if (val < 100)
        kursIndonesia.setMaximumFractionDigits(4);

    return kursIndonesia.format(value);
}

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

/**
 * Format {@link String} like a price with two decimals
 *  //  w  ww .ja v  a  2 s . com
 * WARNING: Only use this method to present data to the screen
 * 
 * @param locale {@link Locale}
 * @param doubleToFormat double to format
 * @return a {@link String} formatted as a price with two decimals assuming the receiver is a float string read from XML
 */
public static String formatPriceWithTwoDecimals(Locale locale, double doubleToFormat) {
    DecimalFormat formatter = new DecimalFormat();
    setupFormatter(formatter, locale, 2);

    return formatter.format(doubleToFormat);
}

From source file:com.cssweb.quote.util.Utils.java

/**
 * ??/*  w w  w . j  a  v  a 2s.  c om*/
 * @param d
 * @param t
 * @return
 */
public static String dataFormation(double d, int t) {
    DecimalFormat df = null;
    switch (t) {
    case 0:
        df = new DecimalFormat("#.##");
        df.setMinimumFractionDigits(0);
        return df.format(d);
    case 1:
        df = new DecimalFormat("#.##");
        df.setMinimumFractionDigits(2);
        return df.format(d);
    case 2:
        df = new DecimalFormat("#.###");
        df.setMinimumFractionDigits(3);
        return df.format(d);
    case 3:
        df = new DecimalFormat("#.####");
        df.setMinimumFractionDigits(4);
        return df.format(d);
    case 4:
        df = new DecimalFormat("#.###%");
        df.setMinimumFractionDigits(3);
        return df.format(d / 100);
    case 5:
        return String.valueOf((int) d);
    case 6:
        df = new DecimalFormat("#.##%");
        df.setMinimumFractionDigits(2);
        return df.format(d);
    case 7:
        df = new DecimalFormat("#.#");
        df.setMinimumFractionDigits(1);
        return df.format(d);
    case 8:
        df = new DecimalFormat("#.##%");
        df.setMinimumFractionDigits(2);
        return df.format(d / 100);
    default:
        return "0";

    }
}

From source file:net.bsrc.cbod.opencv.OpenCV.java

private static void drawComponentsToImage(List<CandidateComponent> candidateComponents,
        CandidateComponent pivot, ImageModel imageModel, String outputSuffix, double fuzzyResult,
        boolean writeFuzzyResult) {

    Mat copy = OpenCV.copyImage(imageModel.getMat());
    Scalar blue = new Scalar(255, 0, 0);
    Scalar green = new Scalar(0, 255, 0);
    Scalar red = new Scalar(0, 0, 255);
    Scalar yellow = new Scalar(0, 255, 255);
    if (candidateComponents != null) {
        for (CandidateComponent cc : candidateComponents) {
            Rect rect = cc.getRect();//from  w  ww.  ja va 2  s .  c o m
            if (cc.getObjectType().equals(EObjectType.WHEEL)) {
                OpenCV.drawRect(rect, copy, red);
            }
            if (cc.getObjectType().equals(EObjectType.TAIL_LIGHT)) {
                OpenCV.drawRect(rect, copy, green);
            }
            if (cc.getObjectType().equals(EObjectType.LICENSE_PLATE)) {
                OpenCV.drawRect(rect, copy, blue);
            }
        }
    }
    if (pivot != null) {
        OpenCV.drawRect(pivot.getRect(), copy, yellow);
    }

    if (writeFuzzyResult) {
        DecimalFormat dFormat = new DecimalFormat("#.####");
        drawText(copy, new Point(5, 20), dFormat.format(fuzzyResult));
    }

    String outputImagePath = CBODUtil.getCbodTempDirectory().concat("/")
            .concat(imageModel.getRawImageName() + outputSuffix + "." + imageModel.getExtension());
    OpenCV.writeImage(copy, outputImagePath);

}

From source file:com.wolvencraft.yasp.util.Util.java

/**
 * Changes a timestamp into a user-friendly form
 *
 * @param timestamp Timestamp to parse/*w w w.  j  a va  2 s  .  co  m*/
 * @return User-friendly output
 */
public static String parseTimestamp(long timestamp) {
    String result = "";
    DecimalFormat f = new DecimalFormat("00");
    int days = (int) (timestamp / 86400);
    int hours = (int) ((timestamp - (days * 86400)) / 3600);
    int minutes = (int) ((timestamp - (days * 86400) - (hours * 3600)) / 60);
    int seconds = (int) (timestamp - (days * 86400) - (hours * 3600) - (minutes * 60));
    if (days != 0)
        result += days + " days, ";
    result += f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
    return result;
}

From source file:com.lm.lic.manager.util.GenUtil.java

public static double roundToTwoDecimals(double d) {
    DecimalFormat twoDecimalFormatter = new DecimalFormat("#.##");
    twoDecimalFormatter.setRoundingMode(RoundingMode.DOWN);
    return Double.valueOf(twoDecimalFormatter.format(d));
}

From source file:com.itude.mobile.mobbl.core.util.StringUtilities.java

public static String formatVolume(String stringToFormat) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }/*from  w w w . j ava2s  .  co m*/

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(getDefaultFormattingLocale()));

    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
    formatter.setMaximumFractionDigits(0);

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

    return result;
}