Example usage for java.text DecimalFormat setRoundingMode

List of usage examples for java.text DecimalFormat setRoundingMode

Introduction

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

Prototype

@Override
public void setRoundingMode(RoundingMode roundingMode) 

Source Link

Document

Sets the java.math.RoundingMode used in this DecimalFormat.

Usage

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * ?   (  ?)/*from  w  w  w  .ja  v a  2  s . c  o m*/
 * @param input
 * @return
 */
public static String decimalPointTwo(Double input) {
    if (input == null || input == 0) {
        return "0.0";
    }
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.FLOOR);
    return df.format(input);
}

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * ??? 100  ? ?? ? (  ?)/*from ww  w.java  2s.  co m*/
 *  ? null ? 0 ? 0.0 ( API   )
 * @param input  ?
 * @return ? ? ? ?
 */
public static String div100(Long input) {
    if (input == null || input == 0) {
        return "0.0";
    }
    Double fl = input / 100d;
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.FLOOR);
    return df.format(fl);
}

From source file:com.feilong.core.text.NumberFormatUtil.java

/**
 *  {@link Number}  {@link RoundingMode} <code>numberPattern</code>?.
 *
 * @param value/*from w  w w .j av a 2s .  com*/
 *            the value
 * @param numberPattern
 *            the pattern {@link NumberPattern}
 * @param roundingMode
 *            ?{@link RoundingMode}
 * @return  <code>value</code> null, {@link NullPointerException}<br>
 *          <code>numberPattern</code> null, {@link NullPointerException}<br>
 *          <code>numberPattern</code> blank, {@link IllegalArgumentException}<br>
 * @see DecimalFormat
 * @see <a href="../util/NumberUtil.html#RoundingMode">JAVA 8??</a>
 */
public static String format(Number value, String numberPattern, RoundingMode roundingMode) {
    Validate.notNull(value, "value can't be null!");
    Validate.notBlank(numberPattern, "numberPattern can't be null!");

    // 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 result = decimalFormat.format(value);
    LOGGER.trace("input:[{}],with:[{}]=[{}],localizedPattern:[{}]", value, numberPattern, result,
            decimalFormat.toLocalizedPattern());
    return result;
}

From source file:com.sunchenbin.store.feilong.core.text.NumberFormatUtil.java

/**
 *  {@link Number}  {@link RoundingMode} numberPattern?.
 *
 * @param value/*from www. j ava  2  s.  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:de.langerhans.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//  w w w  .  j  a  v a 2  s .co m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

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:br.com.itfox.utils.Utils.java

public static String formatDecimal(BigDecimal val) {
    String s = "";
    try {// w ww  .  j  a v a  2  s  .c  om
        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:com.coinblesk.client.utils.UIUtils.java

public static String coinToAmount(Context context, Coin coin) {
    // transform a given coin value to the "amount string".
    BigDecimal coinAmount = new BigDecimal(coin.getValue());
    BigDecimal div = new BigDecimal(Coin.COIN.getValue());

    if (SharedPrefUtils.isBitcoinScaleBTC(context)) {
        div = new BigDecimal(Coin.COIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) {
        div = new BigDecimal(Coin.MILLICOIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) {
        div = new BigDecimal(Coin.MICROCOIN.getValue());
    }/*ww  w.  j ava 2s . co m*/

    DecimalFormat df = new DecimalFormat("#.####");
    df.setRoundingMode(RoundingMode.DOWN);
    df.setMaximumFractionDigits(4);
    DecimalFormatSymbols decFormat = new DecimalFormatSymbols();
    decFormat.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(decFormat);
    String amount = df.format(coinAmount.divide(div));
    return amount;
}

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

public static String formatDecimal(float val) {
    String s = "";
    if (val > 0) {
        try {// w ww.j av a  2s . c  o  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:br.com.itfox.utils.Utils.java

public static String formatDecimal(double val) {
    String s = "";
    if (val > 0) {
        try {/*from  w  ww  .j av a 2  s .com*/
            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;

}