Java Code Examples for java.text.DecimalFormat.setRoundingMode()

The following are Jave code examples for showing how to use setRoundingMode() of the java.text.DecimalFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: gen7-iv-calculator   File: HiddenPowerPresenter.java   Source Code and License Vote up 7 votes
private void displayProbabilities() {
    final DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator(',');
    final DecimalFormat df = new DecimalFormat("", symbols);
    df.setMaximumFractionDigits(1);
    df.setRoundingMode(RoundingMode.HALF_UP);
    df.setMinimumIntegerDigits(1);
    Map<HiddenPower, Double> hiddenPowers = hiddenPowerCalculator.computeHiddenPower(pokemon);
    double badHiddenPower = 0;
    for (final HiddenPower hiddenPower: HiddenPower.values()) {
        double probability = hiddenPowers.get(hiddenPower);
        hiddenPowerLabels.get(hiddenPower.ordinal()).setText(hiddenPower.getName() + ": " + df.format(probability * 100) + "%");
        if (hiddenPower.equals(HiddenPower.WATER) || hiddenPower.equals(HiddenPower.GRASS)) {
            badHiddenPower+= probability;
        }
    }
    feelsBadMan.setVisible(badHiddenPower >= 0.375);
}
 
Example 2
Project: MADBike   File: MapFragment.java   Source Code and License Vote up 6 votes
@Override
public void getWeatherResponse(WeatherResponse weatherResponse) {
    if (weatherResponse.getWeatherItems() != null) {
        setWeatherWidgetImage(weatherResponse.getWeatherItems()[0].getIcon());
        weatherTextView.setText(weatherResponse.getWeatherItems()[0].getDescription());
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        double currentTemp = weatherResponse.getTemperatureItem().getTemp();
        double maxTemp = weatherResponse.getTemperatureItem().getTempMax();
        double minTemp = weatherResponse.getTemperatureItem().getTempMin();
        if (sharedPreferences.getString("degrees_list", "ºC").equalsIgnoreCase("ºF")) {
            currentTemp = (currentTemp * 1.8) + 32;
            maxTemp = (maxTemp * 1.8) + 32;
            minTemp = (minTemp * 1.8) + 32;
        }
        DecimalFormat df = new DecimalFormat("#.#");
        df.setRoundingMode(RoundingMode.CEILING);
        tempTextView.setText(df.format(currentTemp) + sharedPreferences.getString("degrees_list", "ºC"));
        tempMaxTextView.setText(df.format(maxTemp) + sharedPreferences.getString("degrees_list", "ºC"));
        tempMinTextView.setText(df.format(minTemp) + sharedPreferences.getString("degrees_list", "ºC"));
    } else {
        weatherRelativeLayout.setVisibility(View.GONE);
    }
}
 
Example 3
Project: nfse   File: DoubleConversor.java   Source Code and License Vote up 5 votes
public String toString(Object obj){
  DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ROOT);
  symbols.setDecimalSeparator('.');
  symbols.setGroupingSeparator(','); 
  
  DecimalFormat formatDecimal = new DecimalFormat("#0.00", symbols);
  formatDecimal.setRoundingMode(RoundingMode.HALF_UP);
  return formatDecimal.format((Double) obj);
}
 
Example 4
Project: IO   File: ProcessController.java   Source Code and License Vote up 5 votes
@Override
public String toString(Disk disk) {
    if (disk == null) {
        return "";
    }
    double bytesInGB = disk.getSize() / 1073741824.0;
    DecimalFormat df = new DecimalFormat("#.##"); 
    df.setRoundingMode(RoundingMode.CEILING);
    return disk.getName() + ": " + disk.model + " [" +  df.format(bytesInGB) + "GB]";

}
 
Example 5
Project: datarouter   File: NumberFormatter.java   Source Code and License Vote up 5 votes
public static String format(Number number, String prefix, String suffix, int numFractionDigits, boolean grouping){
	DecimalFormat df = new DecimalFormat();
	df.setMaximumFractionDigits(numFractionDigits);
	df.setMinimumFractionDigits(numFractionDigits);
	df.setRoundingMode(RoundingMode.HALF_UP);
	df.setGroupingUsed(grouping);
	df.setPositivePrefix(prefix);
	df.setNegativePrefix(prefix + "-");
	df.setPositiveSuffix(suffix);
	df.setNegativeSuffix(suffix);
	return df.format(number);
}
 
Example 6
Project: lams   File: CurrencyFormatter.java   Source Code and License Vote up 5 votes
@Override
protected NumberFormat getNumberFormat(Locale locale) {
	DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
	format.setParseBigDecimal(true);
	format.setMaximumFractionDigits(this.fractionDigits);
	format.setMinimumFractionDigits(this.fractionDigits);
	if (this.roundingMode != null && roundingModeOnDecimalFormat) {
		format.setRoundingMode(this.roundingMode);
	}
	if (this.currency != null) {
		format.setCurrency(this.currency);
	}
	return format;
}
 
Example 7
Project: util4j   File: TableLottery.java   Source Code and License Vote up 5 votes
public static <T extends TableBlock> String test(Collection<T> tableBlocks,int testCount)
{
	Random seed=new Random();
	String result="";
	int allCount=testCount;
	Map<T,Integer> map=new HashMap<T, Integer>();
	//统计元素出现次数
	for(int i=0;i<allCount;i++)
	{
		T item=randomBlock(tableBlocks, seed);
		if(map.containsKey(item))
		{
			int tmp=map.get(item);
			tmp++;
			map.put(item, tmp);
			
		}else
		{
			map.put(item, 1);
		}
	}
	//计算概率
	for(T key:map.keySet())
	{
		int count=map.get(key);
		DecimalFormat df = new DecimalFormat();  
	    df.setMaximumFractionDigits(2);// 设置精确2位小数   
	    df.setRoundingMode(RoundingMode.HALF_UP); //模式 例如四舍五入   
	    double p = (double)count/(double)allCount*100;//以100为计算概率200为实际总概率,则计算的概率会减半 
	    result="元素:"+key+"出现次数"+count+"/"+allCount+",出现概率:"+df.format(p)+"%";
	    System.out.println("元素:"+key+"出现次数"+count+"/"+allCount+",出现概率:"+df.format(p)+"%");
	}
	return result;
}
 
Example 8
Project: sonar-coverage-evolution   File: CoverageUtils.java   Source Code and License Vote up 5 votes
public static String formatPercentage(double d) {

    // Defining that our percentage is precise down to 0.1%
    DecimalFormat df = new DecimalFormat("0.0");

    // Protecting this method against non-US locales that would not use '.' as decimal separation
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(decimalFormatSymbols);

    // Making sure that we round the 0.1% properly out of the double value
    df.setRoundingMode(RoundingMode.HALF_UP);
    return df.format(d);
  }
 
Example 9
Project: Veggietizer   File: Formatter.java   Source Code and License Vote up 5 votes
/**
 * Rounds <code>days</code> to <code>numDecimals</code> decimals and appends the pluralised "days" string.
 *
 * @param days The number of days to format.
 * @param context The application context.
 * @param quantityId The ID of the pluralised "days" string.
 * @param numDecimals The maximum number of decimals to use. If more would be needed, the days will be rounded.
 * @return The string representation.
 */
public static String formatDays(float days, Context context, int quantityId, int numDecimals) {
    StringBuilder builder = new StringBuilder(PATTERN_BASE + ".");
    for (int i = 0; i < numDecimals; ++i) {
        builder.append("#");
    }
    DecimalFormat decimalFormat = new DecimalFormat(builder.toString());
    int quantity = Math.round(days * 10.0f) == 10 ? 1 : 2;

    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    return decimalFormat.format(days) + '\u00A0' + context.getResources().getQuantityText(quantityId, quantity);
}
 
Example 10
Project: DecimalTextView   File: ParfoisDecimalEditText.java   Source Code and License Vote up 5 votes
/**
 * 格式化数字 double2string
 */
private CharSequence formatDecimal2String(double decimal) {
    String decimalScaleStr = "";
    String s = mDecimalFill ? "0" : "#";
    for (int i = 0; i < mDecimalScale; i++) {
        decimalScaleStr += s;
    }

    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
    if (mShowCommas && !mShowSymbol) { // 显示数字分号 && 不显示数字符号
        formatter.applyPattern(",##0." + decimalScaleStr);
    } else if (mShowCommas) { // 显示数字分号 && 显示数字符号
        formatter.applyPattern(mSymbol + ",##0." + decimalScaleStr);
    } else if (mShowSymbol) { // 不显示数字分号 && 显示数字符号
        formatter.applyPattern(mSymbol + "#0." + decimalScaleStr);
    } else { // 不显示数字分号 && 不显示数字符号
        formatter.applyPattern("#0." + decimalScaleStr);
    }
    formatter.setRoundingMode(RoundingMode.DOWN);

    SpannableStringBuilder result = new SpannableStringBuilder(formatter.format(decimal));
    if (mShowSymbol) {
        if (mSymbolSize == 0) mSymbolSize = getTextSize();
        result.setSpan(new AbsoluteSizeSpan((int) mSymbolSize), 0, mSymbol.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    return result;
}
 
Example 11
Project: nfse   File: DoubleUtil.java   Source Code and License Vote up 4 votes
public static Double arredondarDuasCasas(Double valor){
  DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
  DecimalFormat df = new DecimalFormat("###.##", symbols);
  df.setRoundingMode(RoundingMode.HALF_EVEN);
  return Double.valueOf(df.format(valor));
}
 
Example 12
Project: redpacketui-open   File: RPBaseDialogFragment.java   Source Code and License Vote up 4 votes
public String doubleNumberFormat(double number) {
    DecimalFormat format = new DecimalFormat("###########0.00");
    format.setRoundingMode(RoundingMode.FLOOR);
    return format.format(number);
}
 
Example 13
Project: redpacketui-open   File: RPBaseFragment.java   Source Code and License Vote up 4 votes
public String doubleNumberFormat(double number) {
    DecimalFormat format = new DecimalFormat("###########0.00");
    format.setRoundingMode(RoundingMode.FLOOR);
    return format.format(number);
}
 
Example 14
Project: androdns   File: DNSFormActivity.java   Source Code and License Vote up 4 votes
/**
 * update the the lower gui section with the Values from an AnswerScreenState
 * @param state
 * history: if true, do not update the title
 */
public void updateScreenState(final AnswerScreenState state, final boolean history){



    DecimalFormat df = new DecimalFormat("#.###");
    df.setRoundingMode(RoundingMode.CEILING);
    final String ampFactor = df.format(state.ampFactor);

    Runnable guiUpdate = new Runnable() {
        @Override
        public void run() {
            if (!history){
                setTitle("");
            }

            ((TextView) findViewById(R.id.txtStatusText)).setText(state.status);
            ((TextView) findViewById(R.id.txtServerIP)).setText(state.server);
            ((TextView) findViewById(R.id.txtQbytes)).setText(""+state.qsize);
            ((TextView) findViewById(R.id.txtAbytes)).setText(""+state.asize);
            ((TextView) findViewById(R.id.txtAmpfactor)).setText(ampFactor);
            ((EditText) findViewById(R.id.txtResult)).setText(state.answerText);
            if (state.rcode>-1) {
                ((TextView) findViewById(R.id.txtRcode)).setText(Rcode.string(state.rcode));
            } else {
                ((TextView) findViewById(R.id.txtRcode)).setText("");

            }


            ((CheckBox) findViewById(R.id.cbaAA)).setChecked(  state.flag_AA);
            ((CheckBox) findViewById(R.id.cbaTC)).setChecked(  state.flag_TC);
            ((CheckBox) findViewById(R.id.cbaRD)).setChecked(  state.flag_RD);
            ((CheckBox) findViewById(R.id.cbaRA)).setChecked(  state.flag_RA);
            ((CheckBox) findViewById(R.id.cbaAD)).setChecked(  state.flag_AD);
            ((CheckBox) findViewById(R.id.cbaCD)).setChecked(  state.flag_CD);


        }
    };

    runOnUiThread(guiUpdate);
}
 
Example 15
Project: atlant-android   File: DigitsUtils.java   Source Code and License Vote up 4 votes
private static String formatShow(BigDecimal value) {
  DecimalFormat percentFormat = new DecimalFormat(MASK);
  percentFormat.setDecimalSeparatorAlwaysShown(false);
  percentFormat.setRoundingMode(RoundingMode.DOWN);
  return percentFormat.format(value).replace(',', '.');
}
 
Example 16
Project: oscm   File: ValueRounder.java   Source Code and License Vote up 3 votes
/**
 * Rounds a value by using the specified scale with half up rounding and
 * without grouping. Even if the last part of the decimal value is 0 in
 * specified fraction digits, always all decimal places are filled with 0.
 * (e.g. value 1.2, 5 fraction digits, en locale => '1.20000' will be
 * returned)
 * 
 * @param value
 *            Value to be formatted.
 * @param locale
 *            Current user's locale for formatting.
 * @param fractionDigits
 *            Number of decimal places.
 * @return
 */
public static String roundValue(BigDecimal value, Locale locale,
        int fractionDigits) {
    DecimalFormat df = new DecimalFormat();
    df.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(fractionDigits);
    df.setMinimumFractionDigits(fractionDigits);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return df.format(value);
}
 
Example 17
Project: FCat   File: MathUtil.java   Source Code and License Vote up 3 votes
/**
 * 功能:格式化双精度数,四舍五入 <br>
 * 
 * @param d
 * @param pattern
 *            ########0<br>
 *            ########0.0<br>
 *            ########0.00<br>
 *            ########0.000<br>
 *            ########0.0000<br>
 *            ########0.00000<br>
 *            ##.######最高6位精度123.456789 等
 * @param roundingMode
 *            {@link RoundingMode#HALF_UP}
 * @return
 */
public static String formatDouble(double d, String pattern, RoundingMode roundingMode) {
	String result = "Format Error";
	if (pattern == null || "".equals(pattern))
		pattern = "########0.00";
	try {
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		decimalFormat.setRoundingMode(roundingMode);
		result = decimalFormat.format(d);
	} catch (Exception e) {
		// LOG.error(e.getMessage(), e);
	}
	return result;
}
 
Example 18
Project: MooProject   File: NumberUtil.java   Source Code and License Vote up 2 votes
/**
 * Rounds given number to n-places after the comma
 *
 * @param x The number
 * @param n The value (n)
 * @return The formatted string
 */
public static String round(double x, int n) {
    DecimalFormat df = new DecimalFormat("#." + Strings.repeat("#", n));
    df.setRoundingMode(RoundingMode.CEILING);
    return df.format(x);
}