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

The following examples show how to use java.text.DecimalFormat#setMaximumFractionDigits() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LiteralProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public String format(BigDecimal number) {
	try {
		// TODO : what amount of significant digits need to be supported here?
		//      - from the DecimalFormat docs:
		//          [significant digits] = [minimum integer digits] + [maximum fraction digits]
		DecimalFormat jdkFormatter = new DecimalFormat( FORMAT_STRING );
		jdkFormatter.setMinimumIntegerDigits( 1 );
		jdkFormatter.setMaximumFractionDigits( Integer.MAX_VALUE );
		return jdkFormatter.format( number );
	}
	catch (Throwable t) {
		throw new HibernateException(
				"Unable to format decimal literal in approximate format [" + number.toString() + "]",
				t
		);
	}
}
 
Example 2
Source File: NumberFormatProviderImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example 3
Source File: MonetaryUtil.java    From zap-android with MIT License 6 votes vote down vote up
private String formatAsBitsDisplayAmount(long value) {
    Locale loc = mContext.getResources().getConfiguration().locale;
    NumberFormat nf = NumberFormat.getNumberInstance(loc);
    DecimalFormat df = (DecimalFormat) nf;
    df.setMaximumFractionDigits(2);
    df.setMinimumIntegerDigits(1);
    df.setMaximumIntegerDigits(22);
    String result = df.format(value / 100d);

    // If we have a fraction, then always show 2 fraction digits for bits
    if (result.contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
        df.setMinimumFractionDigits(2);
        return df.format(value / 100d);
    } else {
        return result;
    }
}
 
Example 4
Source File: NumberFormatProviderImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example 5
Source File: OdsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static String formatNumberAsDecimal( Object data )
{
	Number number=(Number)data;
	DecimalFormat numberFormat = new DecimalFormat( "0.##############" );
	numberFormat.setMaximumFractionDigits( 15 );
	updateDecimalSeparator( numberFormat );
	return numberFormat.format( number );
}
 
Example 6
Source File: EBIMatrix.java    From ReactionDecoder with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 dataolumn width.
 * @param d Number of digits after the decimal.
 */
public synchronized void print(PrintWriter output, int w, int d) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);
    print(output, format, w + 2);
}
 
Example 7
Source File: Treatments.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static List<Treatments> latestForGraph(int number, double startTime, double endTime) {
    fixUpTable();
    DecimalFormat df = new DecimalFormat("#");
    df.setMaximumFractionDigits(1); // are there decimal points in the database??
    return new Select()
            .from(Treatments.class)
            .where("timestamp >= ? and timestamp <= ?", df.format(startTime), df.format(endTime))
            .orderBy("timestamp asc")
            .limit(number)
            .execute();
}
 
Example 8
Source File: CsvData.java    From typometer with Apache License 2.0 5 votes vote down vote up
private static DecimalFormat createDecimalFormat(Locale locale, int fractionDigits) {
    DecimalFormat result = new DecimalFormat();
    result.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
    result.setMinimumFractionDigits(fractionDigits);
    result.setMaximumFractionDigits(fractionDigits);
    result.setGroupingUsed(false);
    return result;
}
 
Example 9
Source File: Plot.java    From FancyBing with GNU General Public License v3.0 5 votes vote down vote up
private DecimalFormat getFormat(boolean onlyIntValues)
{
    DecimalFormat format = new DecimalFormat();
    format.setGroupingUsed(false);
    if (onlyIntValues)
        format.setMaximumFractionDigits(0);
    else
        format.setMaximumFractionDigits(m_precision);
    return format;
}
 
Example 10
Source File: SimpleCostEstimate.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String prettyDmlStmtString(double cost, long rows, String attrDelim, String rowsLabel) {
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(3);
    df.setGroupingUsed(false);
    StringBuilder sb = new StringBuilder();
    sb.append("totalCost=").append(df.format(cost/1000));
    sb.append(attrDelim).append(rowsLabel == null ? "outputRows" : rowsLabel).append("=").append(rows);
    return sb.toString();
}
 
Example 11
Source File: CurrencyCache.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
public static DecimalFormat createCurrencyFormat(Currency c) {
	DecimalFormatSymbols dfs = new DecimalFormatSymbols();
	dfs.setDecimalSeparator(charOrEmpty(c.decimalSeparator, dfs.getDecimalSeparator()));
	dfs.setGroupingSeparator(charOrEmpty(c.groupSeparator, dfs.getGroupingSeparator()));
	dfs.setMonetaryDecimalSeparator(dfs.getDecimalSeparator());
	dfs.setCurrencySymbol(c.symbol);

	DecimalFormat df = new DecimalFormat("#,##0.00", dfs);
	df.setGroupingUsed(dfs.getGroupingSeparator() > 0);
	df.setMinimumFractionDigits(c.decimals);
	df.setMaximumFractionDigits(c.decimals);
	df.setDecimalSeparatorAlwaysShown(false);
	return df;
}
 
Example 12
Source File: Bg.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
public String unitizedDeltaStringNoUnit() {
    DecimalFormat df = new DecimalFormat("#");
    df.setMaximumFractionDigits(1);
    String delta_sign = "";
    if (bgdelta > 0.1) { delta_sign = "+"; }
    if(doMgdl()) {
        return delta_sign + df.format(unitized(bgdelta));
    } else {
        return delta_sign + df.format(unitized(bgdelta));
    }
}
 
Example 13
Source File: Unitized.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String unitized_string(double value, boolean doMgdl) {
    final DecimalFormat df = new DecimalFormat("#");
    if (value >= 400) {
        return "HIGH";
    } else if (value >= 40) {
        if (doMgdl) {
            df.setMaximumFractionDigits(0);
            return df.format(value);
        } else {
            df.setMaximumFractionDigits(1);
            //next line ensures mmol/l value is XX.x always.  Required by PebbleWatchSync, and probably not a bad idea.
            df.setMinimumFractionDigits(1);
            return df.format(mmolConvert(value));
        }
    } else if (value > 12) {
        return "LOW";
    } else {
        switch ((int) value) {
            case 0:
                return "??0";
            case 1:
                return "?SN";
            case 2:
                return "??2";
            case 3:
                return "?NA";
            case 5:
                return "?NC";
            case 6:
                return "?CD";
            case 9:
                return "?AD";
            case 12:
                return "?RF";
            default:
                return "???";
        }
    }
}
 
Example 14
Source File: FileSize.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private static String format(final long value,
                             final long divider,
                             final String unit) {
  final double result =
      divider > 1 ? (double) value / (double) divider : (double) value;
  DecimalFormat decimalFormat = new DecimalFormat();
  decimalFormat.setMaximumFractionDigits(1);
  decimalFormat.setMinimumFractionDigits(0);
  decimalFormat.setGroupingUsed(false);
  decimalFormat.setDecimalSeparatorAlwaysShown(false);
  return decimalFormat.format(result) + " " + unit;
}
 
Example 15
Source File: StringFormatting.java    From thunderstorm with GNU General Public License v3.0 5 votes vote down vote up
public static DecimalFormat getDecimalFormat(int floatPrecision) {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
    symbols.setInfinity("Infinity");
    symbols.setNaN("NaN");
    df.setDecimalFormatSymbols(symbols);
    df.setGroupingUsed(false);
    df.setRoundingMode(RoundingMode.HALF_EVEN);
    df.setMaximumFractionDigits(floatPrecision);
    return df;
}
 
Example 16
Source File: StringUtil.java    From graql with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param value a value in the graph
 * @return the string representation of the value (using quotes if it is already a string)
 */
public static String valueToString(Object value) {
    if (value instanceof String) {
        return quoteString((String) value);
    } else if (value instanceof Double) {
        DecimalFormat df = new DecimalFormat("#", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(12);
        df.setMinimumIntegerDigits(1);
        return df.format(value);
    } else {
        return value.toString();
    }
}
 
Example 17
Source File: Matrix.java    From citygml4j with Apache License 2.0 5 votes vote down vote up
/** 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 18
Source File: ValueStatsTest.java    From datakernel with Apache License 2.0 5 votes vote down vote up
private void assertNumberOfDigitsAfterDot(ValueStats stats) {
	String statsString = stats.toString();
	String formattedMin = statsString.substring(statsString.indexOf('[') + 1, statsString.indexOf("..."));
	String formattedMax = statsString.substring(statsString.indexOf("...") + 3, statsString.indexOf("]"));

	int log = (int) floor(log10(stats.getSmoothedMax() - stats.getSmoothedMin()) - 3);
	int numberOfDigits = log > 0 ? 0 : -log;
	numberOfDigits = Math.min(numberOfDigits, 6);
	DecimalFormat format = new DecimalFormat("0");
	format.setMaximumFractionDigits(numberOfDigits);

	assertEquals(format.format(stats.getSmoothedMin()), formattedMin);
	assertEquals(format.format(stats.getSmoothedMax()), formattedMax);
}
 
Example 19
Source File: FormatKit.java    From 600SeriesAndroidUploader with MIT License 4 votes vote down vote up
public String formatAsGlucoseMMOL(int value, boolean tag, int precision) {
    DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.getDefault()));
    df.setMinimumFractionDigits(1);
    df.setMaximumFractionDigits(precision);
    return df.format(value / MMOLXLFACTOR) + (tag ? " " + mApplication.getApplicationContext().getString(R.string.glucose_mmol) : "");
}
 
Example 20
Source File: CalibrationGraph.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public void setupCharts() {
    chart = (LineChartView) findViewById(R.id.chart);
    List<Line> lines = new ArrayList<Line>();

    //calibration values
    List<Calibration> calibrations = Calibration.allForSensor();
    List<Line> greyLines = getCalibrationsLine(calibrations, Color.parseColor("#66FFFFFF"));
    calibrations = Calibration.allForSensorInLastFourDays();
    List<Line> blueLines = getCalibrationsLine(calibrations, ChartUtils.COLOR_BLUE);

    Calibration calibration = Calibration.lastValid();
    if (calibration != null) {
        //set header
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(2);
        df.setMinimumFractionDigits(2);
        String Header = "slope = " + df.format(calibration.slope) + " intercept = " + df.format(calibration.intercept);
        GraphHeader.setText(Header);

        //red line
        List<PointValue> lineValues = new ArrayList<PointValue>();
        final float conversion_factor = (float) (doMgdl ? 1 : Constants.MGDL_TO_MMOLL);

        lineValues.add(new PointValue((float) start_x, (conversion_factor * (float) (start_x * calibration.slope + calibration.intercept))));
        lineValues.add(new PointValue((float) end_x, (conversion_factor * (float) (end_x * calibration.slope + calibration.intercept))));
        Line calibrationLine = new Line(lineValues);
        calibrationLine.setColor(ChartUtils.COLOR_RED);
        calibrationLine.setHasLines(true);
        calibrationLine.setHasPoints(false);
        lines.add(calibrationLine);

        // calibration plugin
        final CalibrationAbstract plugin = getCalibrationPluginFromPreferences();
        if (plugin != null) {
            final CalibrationAbstract.CalibrationData pcalibration = plugin.getCalibrationData();

            final List<PointValue> plineValues = new ArrayList<PointValue>();

            plineValues.add(new PointValue((float) start_x, (conversion_factor * (float) (plugin.getGlucoseFromSensorValue(start_x, pcalibration)))));
            plineValues.add(new PointValue((float) end_x, (conversion_factor * (float) (plugin.getGlucoseFromSensorValue(end_x, pcalibration)))));

            final Line pcalibrationLine = new Line(plineValues);
            pcalibrationLine.setColor(Color.parseColor(plugin_color));
            pcalibrationLine.setHasLines(true);
            pcalibrationLine.setHasPoints(false);
            lines.add(pcalibrationLine);
            PluginHeader.setText("(" + plugin.getAlgorithmName() + ")  " + "s = " + df.format(pcalibration.slope) + "  i = " + df.format(pcalibration.intercept));
            PluginHeader.setTextColor(Color.parseColor(plugin_color));
        }

        //add lines in order
        for (Line greyLine : greyLines) {
            lines.add(greyLine);
        }
        for (Line blueLine : blueLines) {
            lines.add(blueLine);
        }

    }
    Axis axisX = new Axis();
    Axis axisY = new Axis().setHasLines(true);
    axisX.setName("Raw Value");
    axisY.setName("Glucose " + (doMgdl ? "mg/dl" : "mmol/l"));


    data = new LineChartData(lines);
    data.setAxisXBottom(axisX);
    data.setAxisYLeft(axisY);
    chart.setLineChartData(data);

}