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

The following are Jave code examples for showing how to use setMaximumFractionDigits() 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: angel   File: StringUtils.java   Source Code and License Vote up 7 votes
public static String formatPercent(double done, int digits) {
  DecimalFormat percentFormat = new DecimalFormat("0.00%");
  double scale = Math.pow(10.0D, digits + 2);
  double rounded = Math.floor(done * scale);
  percentFormat.setDecimalSeparatorAlwaysShown(false);
  percentFormat.setMinimumFractionDigits(digits);
  percentFormat.setMaximumFractionDigits(digits);
  return percentFormat.format(rounded / scale);
}
 
Example 2
Project: OpenJSharp   File: NumberFormatProviderImpl.java   Source Code and License Vote up 7 votes
private NumberFormat getInstance(Locale locale,
                                        int choice) {
    if (locale == null) {
        throw new NullPointerException();
    }

    LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
    String[] numberPatterns = adapter.getLocaleResources(locale).getNumberPatterns();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        adjustForCurrencyDefaultFractionDigits(format, symbols);
    }

    return format;
}
 
Example 3
Project: queryfy   File: NumberVar.java   Source Code and License Vote up 6 votes
private void build() {
    try {

        if (typeQualifier != null) {
            buildQualifiedNumber();
            return;
        }

        Number value;
        if (number.contains(".")) {
            DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
            decimalFormat.setParseBigDecimal(true);

            int decSymbolIndex = number.lastIndexOf(".");
            if (decSymbolIndex > -1) {
                int precision = number.substring(decSymbolIndex, number.length() - 1).length();
                decimalFormat.setMaximumFractionDigits(precision);
            }

            value = decimalFormat.parse(number);
        } else {
            value = NumberFormat.getInstance(locale).parse(number);
        }

        set(value);
    } catch (ParseException e) {
        throw new RuntimeException(String.format("Invalid number '%s'", number));
    }
}
 
Example 4
Project: RunMap   File: FunctionFragPresenterImpl.java   Source Code and License Vote up 6 votes
@Override
public void updateTotalDistance(Context context) {
    if(context != null){
        SharedPreferences sp = context.getSharedPreferences(RMConfiguration.FILE_CONFIG, Context.MODE_PRIVATE);
        long distance = sp.getLong(RMConfiguration.KEY_TOTAL_DISTANCE,0);
        long tmpDistance = sp.getLong(RMConfiguration.KEY_TMP_DISTANCE,0);
        if(tmpDistance < 0){
            return;
        }
        distance += tmpDistance;
        //if there have an effective value, update it now
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(RMConfiguration.KEY_TMP_DISTANCE,0);
        editor.putLong(RMConfiguration.KEY_TOTAL_DISTANCE,distance);
        editor.commit();
        DecimalFormat distanceFormater = (DecimalFormat) NumberFormat.getInstance();
        distanceFormater.setMinimumFractionDigits(2);
        distanceFormater.setMaximumFractionDigits(2);
        mFunctionFragment.showUpgradeDistance(distanceFormater.format(distance/1000.0));
    }
}
 
Example 5
Project: Custom-Vison-Service   File: NutritionActivity.java   Source Code and License Vote up 6 votes
public void prepareChartData(Hit hit){
        entries = new ArrayList<BarEntry>();
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(2);

        entries.add(new BarEntry(0, (float) (hit.getFields().getNfCalories()/2000)*100));
        entries.add(new BarEntry(1, (float) (hit.getFields().getNfTotalFat()/65)*100));
        entries.add(new BarEntry(2, (float) (hit.getFields().getNfCholesterol()/300)*100));
        entries.add(new BarEntry(3, (float)(hit.getFields().getNfSodium()/2400)*100));
        entries.add(new BarEntry(4, (float)(hit.getFields().getNfTotalCarbohydrate()/300)*100));
        entries.add(new BarEntry(5, (float) hit.getFields().getNfSodium()));
        entries.add(new BarEntry(6, (float) (hit.getFields().getNfProtein()/50)*100));
//        entries.add(new BarEntry(7, (float) hit.getFields().getNfVitaminADv(), "(mg)"));
//        entries.add(new BarEntry(8, (float) hit.getFields().getNfVitaminCDv(), "(mg)"));
//        entries.add(new BarEntry(9, (float) hit.getFields().getNfCalciumDv(), "(mg)"));

        BarDataSet dataSet = new BarDataSet(entries, String.format("%s Nutrition", food_item).toUpperCase());

        setChartData(dataSet);
    }
 
Example 6
Project: 5zig-TIMV-Plugin   File: KDRChangeItem.java   Source Code and License Vote up 5 votes
@Override
protected Object getValue(boolean dummy) {
	try{		
		
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		df.setMinimumFractionDigits(2);
		
		return df.format(BED.gameKdr) + " (" + (BED.gameKdr - BED.apiKdr > 0 ? "+" + df.format(BED.gameKdr - BED.apiKdr) : df.format(BED.gameKdr - BED.apiKdr)) + ")";
	}catch(Exception e){
			e.printStackTrace();
			return "Server error";
	}
}
 
Example 7
Project: Apriori   File: RuleSet.java   Source Code and License Vote up 5 votes
@Override
public final String toString() {
    StringBuilder stringBuilder = new StringBuilder();
    DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setMinimumFractionDigits(1);
    decimalFormat.setMaximumFractionDigits(2);
    Iterator<AssociationRule<ItemType>> iterator = iterator();
    stringBuilder.append("[");

    while (iterator.hasNext()) {
        AssociationRule<ItemType> rule = iterator.next();
        stringBuilder.append(rule.toString());
        stringBuilder.append(" (support = ");
        stringBuilder.append(decimalFormat.format(new Support().evaluate(rule)));
        stringBuilder.append(", confidence = ");
        stringBuilder.append(decimalFormat.format(new Confidence().evaluate(rule)));
        stringBuilder.append(", lift = ");
        stringBuilder.append(decimalFormat.format(new Lift().evaluate(rule)));
        stringBuilder.append(", leverage = ");
        stringBuilder.append(decimalFormat.format(new Leverage().evaluate(rule)));
        stringBuilder.append(")");

        if (iterator.hasNext()) {
            stringBuilder.append(",\n");
        }
    }

    stringBuilder.append("]");
    return stringBuilder.toString();
}
 
Example 8
Project: FuelUp   File: EditFillUpActivity.java   Source Code and License Vote up 5 votes
@Override
protected void onStart() {
    super.onStart();

    mTxtDistance.setText(mSelectedFillUp.getDistanceFromLastFillUp().toString());
    mTxtFuelVolumeUnit.setText(mVehicle.getVolumeUnit().toString());
    mTxtFuelVolume.setText(NumberFormat.getNumberInstance().format(mSelectedFillUp.getFuelVolume()));
    this.onCheckedChanged(mBtnSwitchPrice, false);
    if (priceMode == SwitchPrice.perVolume) {
        Currency currency = mVehicle.getCurrency();
        DecimalFormat formatter = BigDecimalFormatter.getCommonFormat();

        formatter.setMaximumFractionDigits(CurrencyUtil.getPerLitreFractionDigits(currency) + 1);
        formatter.setMinimumFractionDigits(CurrencyUtil.getPerLitreFractionDigits(currency));

        mTxtPrice.setText(formatter.format(mSelectedFillUp.getFuelPricePerLitre().multiply(CurrencyUtil.getCoefficientPerLitreMultiply(mSelectedFillUp.getVehicle().getCurrency()))));
    } else {
        mTxtPrice.setText(BigDecimalFormatter.getCommonFormat().format(mSelectedFillUp.getFuelPriceTotal()));
    }
    mCheckBoxIsFullFill.setChecked(mSelectedFillUp.isFullFillUp());

    mTxtInfo.setText(mSelectedFillUp.getInfo());

    setFillUpDate(DateUtil.transformToCal(mSelectedFillUp.getDate()));

    mBtnAdd.setText(R.string.update);

    mTxtDistanceUnit.setText(mVehicle.getDistanceUnit().toString());

    distanceMode = SwitchDistance.fromLast;
    isWholeDistanceTyped.setVisibility(View.GONE);
}
 
Example 9
Project: morpheus-core   File: Matrix.java   Source Code and License Vote up 5 votes
/** Print the matrix to the output stream.   Line the elements up in
  * columns with a Fortran-like 'Fw.d' style format.
@param output Output stream.
@param w      Column width.
@param d      Number of digits after the decimal.
*/

public void print (PrintWriter output, int w, int d) {
   DecimalFormat format = new DecimalFormat();
   format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
   format.setMinimumIntegerDigits(1);
   format.setMaximumFractionDigits(d);
   format.setMinimumFractionDigits(d);
   format.setGroupingUsed(false);
   print(output,format,w+2);
}
 
Example 10
Project: okwallet   File: BtcFormat.java   Source Code and License Vote up 5 votes
/** Sets the number of fractional decimal places to be displayed on the given
 *  NumberFormat object to the value of the given integer.
 *  @return The minimum and maximum fractional places settings that the
 *          formatter had before this change, as an ImmutableList. */
private static ImmutableList<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) {
    ImmutableList<Integer> ante = ImmutableList.of(
        formatter.getMinimumFractionDigits(),
        formatter.getMaximumFractionDigits()
    );
    formatter.setMinimumFractionDigits(min);
    formatter.setMaximumFractionDigits(max);
    return ante;
}
 
Example 11
Project: intellij-randomness   File: DecimalInsertAction.java   Source Code and License Vote up 5 votes
/**
 * Returns a nicely formatted representation of a double.
 *
 * @param decimal a {@code double}
 * @return a nicely formatted representation of a double
 */
private String convertToString(final double decimal) {
    final DecimalFormat format = new DecimalFormat();
    format.setGroupingUsed(decimalSettings.getGroupingSeparator() != '\0');

    final DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(decimalSettings.getGroupingSeparator());
    symbols.setDecimalSeparator(decimalSettings.getDecimalSeparator());
    format.setMinimumFractionDigits(decimalSettings.getDecimalCount());
    format.setMaximumFractionDigits(decimalSettings.getDecimalCount());
    format.setDecimalFormatSymbols(symbols);

    return format.format(decimal);
}
 
Example 12
Project: oscm   File: PriceConverter.java   Source Code and License Vote up 5 votes
@Override
protected Format getFormat(String pattern, Locale locale) {
    DecimalFormat format = (DecimalFormat) super.getFormat(pattern,
            locale);
    format.setMaximumIntegerDigits(NUMBER_OF_INTEGER_PLACES);
    format.setMaximumFractionDigits(NUMBER_OF_DECIMAL_PLACES);
    // avoid lost precision due to parsing to double:
    format.setParseBigDecimal(true);
    return format;
}
 
Example 13
Project: FuelUp   File: ListFillUpsAdapter.java   Source Code and License Vote up 5 votes
public ListFillUpsAdapter(Callback callback, Vehicle vehicle) {
    super();

    this.mVehicle = vehicle;
    this.mCallback = callback;

    int consumptionFractionDigits = mVehicle.getDistanceUnit() == DistanceUnit.mi ? 1 : 2;
    consumptionFormat = new DecimalFormat();
    consumptionFormat.setGroupingUsed(false);
    consumptionFormat.setMinimumFractionDigits(consumptionFractionDigits);
    consumptionFormat.setMaximumFractionDigits(consumptionFractionDigits);
}
 
Example 14
Project: QN-ACTR-Release   File: CSVLogger.java   Source Code and License Vote up 5 votes
/**
 * Creates a new CSVLogger that writes to the given file
 * @param file the file we should write to
 * @param columns the columns for the log file
 * @param append true to append to an existing file. False to create a new file
 * @param colSep the column separator
 * @param digitSep the decimal digits separator
 */
public CSVLogger(File file, String[] columns, boolean append, String colSep, char digitSep) {
	this.file = file;
	this.initialized = false;
	this.append = append;
	this.columns = columns;
	this.colSep = colSep;
	
	DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
	dfs.setDecimalSeparator(digitSep);
	numberFormat = new DecimalFormat("#.#", dfs);
	numberFormat.setMaximumFractionDigits(340);
	numberFormat.setMaximumIntegerDigits(340);
}
 
Example 15
Project: MapAnalyst   File: Matrix.java   Source Code and License Vote up 5 votes
/** Print the matrix to the output stream.   Line the elements up in
  * columns with a Fortran-like 'Fw.d' style format.
@param output Output stream.
@param w      Column width.
@param d      Number of digits after the decimal.
*/

public void print (PrintWriter output, int w, int d) {
   DecimalFormat format = new DecimalFormat();
   format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
   format.setMinimumIntegerDigits(1);
   format.setMaximumFractionDigits(d);
   format.setMinimumFractionDigits(d);
   format.setGroupingUsed(false);
   print(output,format,w+2);
}
 
Example 16
Project: creacoinj   File: BtcFormat.java   Source Code and License Vote up 5 votes
/** Sets the number of fractional decimal places to be displayed on the given
 *  NumberFormat object to the value of the given integer.
 *  @return The minimum and maximum fractional places settings that the
 *          formatter had before this change, as an ImmutableList. */
private static ImmutableList<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) {
    ImmutableList<Integer> ante = ImmutableList.of(
        formatter.getMinimumFractionDigits(),
        formatter.getMaximumFractionDigits()
    );
    formatter.setMinimumFractionDigits(min);
    formatter.setMaximumFractionDigits(max);
    return ante;
}
 
Example 17
Project: FuelUp   File: VolumeUtil.java   Source Code and License Vote up 5 votes
public static String getFuelVolume(double value) {
    DecimalFormat bddf = new DecimalFormat();
    bddf.setGroupingUsed(false);
    bddf.setMaximumFractionDigits(2);
    bddf.setMinimumFractionDigits(0);

    return bddf.format(value);
}
 
Example 18
Project: FuelUp   File: VolumeUtil.java   Source Code and License Vote up 5 votes
public static DecimalFormat getFormatterForConsumption(String consumptionUnit) {
    DecimalFormat format = new DecimalFormat();

    if (MainActivity.getInstance().getString(R.string.units_mpg).equals(consumptionUnit)) {
        format.setMaximumFractionDigits(1);
        format.setMinimumFractionDigits(1);
    } else {
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
    }

    return format;
}
 
Example 19
Project: intellij-randomness   File: IntegerInsertAction.java   Source Code and License Vote up 5 votes
/**
 * Returns a nicely formatted representation of a long.
 *
 * @param integer a {@code long}
 * @return a nicely formatted representation of a long
 */
private String convertToString(final long integer) {
    final DecimalFormat format = new DecimalFormat();
    format.setGroupingUsed(integerSettings.getGroupingSeparator() != '\0');

    final DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(integerSettings.getGroupingSeparator());
    format.setMinimumFractionDigits(0);
    format.setMaximumFractionDigits(0);
    format.setDecimalFormatSymbols(symbols);

    return format.format(integer);
}
 
Example 20
Project: fiery   File: SQLStatistic.java   Source Code and License Vote up 4 votes
private String getPercent(int a, int b) {
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);
    return df.format(a * 100.00 / b) + "%";
}