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

The following examples show how to use java.text.DecimalFormat#setGroupingUsed() . 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: FormatHelper.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Format a grade using the locale
 *
 * @param grade - string representation of a grade
 * @param locale
 * @return
 */
private static String formatGradeForLocale(final String grade, final Locale locale) {
	if (StringUtils.isBlank(grade)) {
		return "";
	}

	String s;
	try {
		final DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(locale);
		final Double d = df.parse(grade).doubleValue();

		df.setMinimumFractionDigits(0);
		df.setGroupingUsed(false);

		s = df.format(d);
	} catch (final NumberFormatException | ParseException e) {
		log.warn("Bad format, returning original string: {}", grade);
		s = grade;
	}

	return StringUtils.removeEnd(s, ".0");
}
 
Example 2
Source File: U.java    From BeamFour with GNU General Public License v2.0 6 votes vote down vote up
static String fwd(double x, int w, int d)
// converts a double to a string with given width and decimals.
{
    NumberFormat nf = NumberFormat.getInstance(Locale.US); 
    DecimalFormat df = (DecimalFormat) nf;
    df.setMaximumFractionDigits(d); 
    df.setMinimumFractionDigits(d);
    df.setGroupingUsed(false);   
    String s = df.format(x); 
    while (s.length() < w)
      s = " " + s;  
    if (s.length() > w)
    {
        s = "";
        for (int i=0; i<w; i++)
          s = s + "-";
    }  
    return s; 
}
 
Example 3
Source File: Matrix.java    From biojava with GNU Lesser General Public License v2.1 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 4
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static void assertDecimalFormatIsLossless(double d) throws Exception {
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
    DecimalFormat format = new DecimalFormat("#0.#", dfs);
    format.setGroupingUsed(false);
    format.setMaximumIntegerDigits(400);
    format.setMaximumFractionDigits(400);

    // Every floating point binary can be represented exactly in decimal if you have enough
    // digits. This shows the value actually being tested.
    String testId = "decimalValue: " + new BigDecimal(d);

    // As a sanity check we try out parseDouble() with the string generated by
    // Double.toString(). Strictly speaking Double.toString() is probably not guaranteed to be
    // lossless, but in reality it probably is, or at least is close enough.
    assertDoubleEqual(
            testId + " failed parseDouble(toString()) sanity check",
            d, Double.parseDouble(Double.toString(d)));

    // Format the number: If this is lossy it is a problem. We are trying to check that it
    // doesn't lose any unnecessary precision.
    String result = format.format(d);

    // Here we use Double.parseDouble() which should able to parse a number we know was
    // representable as a double into the original double. If parseDouble() is not implemented
    // correctly the test is invalid.
    double doubleParsed = Double.parseDouble(result);
    assertDoubleEqual(testId + " (format() produced " + result + ")",
            d, doubleParsed);

    // For completeness we try to parse using the formatter too. If this fails but the format
    // above didn't it may be a problem with parse(), or with format() that we didn't spot.
    assertDoubleEqual(testId + " failed parse(format()) check",
            d, format.parse(result).doubleValue());
}
 
Example 5
Source File: MagicSquareExampleFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public static String fixedWidthDoubletoString (final double x, final int w, final int d)
{
  final DecimalFormat fmt = (DecimalFormat) NumberFormat.getNumberInstance (CGlobal.DEFAULT_LOCALE);
  fmt.setMaximumFractionDigits (d);
  fmt.setMinimumFractionDigits (d);
  fmt.setGroupingUsed (false);
  final String s = fmt.format (x);
  return StringHelper.getWithLeading (s, w, ' ');
}
 
Example 6
Source File: DoubleTools.java    From JANNLab with GNU General Public License v3.0 5 votes vote down vote up
public static String asString(
        final double[] data, 
        final String delimiter,
        final int offset, 
        final int step, final int size,
        final int decimals
) {
    StringWriter out = new StringWriter();
    
    DecimalFormat f = new DecimalFormat();
    f.setDecimalSeparatorAlwaysShown(true);
    f.setMaximumFractionDigits(decimals);
    f.setMinimumFractionDigits(decimals);
    f.setGroupingUsed(false);
    
    f.setDecimalFormatSymbols(new DecimalFormatSymbols() {
        private static final long serialVersionUID = -2464236658633690492L;
        public char getGroupingSeparator() { return ' '; }
        public char getDecimalSeparator() { return '.'; }
    });
        
    int o = offset;
    for (int i = 0; i < size; i++) {
        if (i > 0) out.append(delimiter);
        out.append(f.format(data[o]));
        o += step;
    }
    return out.toString();
}
 
Example 7
Source File: PriceConverter.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the formatted value as a String, which is displayed for a given
 * price of type BigDecimal. The formatting used takes into account the
 * given locale, and optionally a grouping separator based on the locale.
 * 
 * @param price
 *            the price as a BigDecimal to be formatted.
 * @param useGrouping
 *            a flag indicating whether a grouping for the formatting will
 *            be used or not.
 * @param locale
 *            the locale to use for the formatting.
 * @return the displayed price formatted value as a String.
 */
public String getValueToDisplay(BigDecimal price, boolean useGrouping,
        Locale locale) {

    DecimalFormat nf = new DecimalFormat();
    nf.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
    nf.setGroupingUsed(useGrouping);
    nf.setMinimumFractionDigits(MINIMUM_FRACTION_DIGIT);
    if (useGrouping) {
        nf.applyPattern(PriceConverter.FORMAT_PATTERN_WITH_GROUPING);
    } else {
        nf.applyPattern(PriceConverter.FORMAT_PATTERN_WITHOUT_GROUPING);
    }

    String formattedPrice;
    if (price == null) {
        formattedPrice = nf.format(BigDecimal.ZERO);

    } else {
        if (price.scale() > MINIMUM_FRACTION_DIGIT) {
            nf.setMaximumFractionDigits(price.scale());
        }
        formattedPrice = nf.format(price);
    }
    return formattedPrice;

}
 
Example 8
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 9
Source File: Fixed.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ValueEval fixed(
        ValueEval numberParam, ValueEval placesParam,
        ValueEval skipThousandsSeparatorParam,
        int srcRowIndex, int srcColumnIndex) {
    try {
        ValueEval numberValueEval =
                OperandResolver.getSingleValue(
                numberParam, srcRowIndex, srcColumnIndex);
        BigDecimal number =
                new BigDecimal(OperandResolver.coerceValueToDouble(numberValueEval));
        ValueEval placesValueEval =
                OperandResolver.getSingleValue(
                placesParam, srcRowIndex, srcColumnIndex);
        int places = OperandResolver.coerceValueToInt(placesValueEval);
        ValueEval skipThousandsSeparatorValueEval =
                OperandResolver.getSingleValue(
                skipThousandsSeparatorParam, srcRowIndex, srcColumnIndex);
        Boolean skipThousandsSeparator =
                OperandResolver.coerceValueToBoolean(
                skipThousandsSeparatorValueEval, false);
        
        // Round number to respective places.
        number = number.setScale(places, RoundingMode.HALF_UP);
        
        // Format number conditionally using a thousands separator.
        NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
        DecimalFormat formatter = (DecimalFormat)nf;
        formatter.setGroupingUsed(!(skipThousandsSeparator != null && skipThousandsSeparator));
        formatter.setMinimumFractionDigits(places >= 0 ? places : 0);
        formatter.setMaximumFractionDigits(places >= 0 ? places : 0);
        String numberString = formatter.format(number.doubleValue());

        // Return the result as a StringEval.
        return new StringEval(numberString);
    } catch (EvaluationException e) {
        return e.getErrorEval();
    }
}
 
Example 10
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_formatDouble_roundingTo15Digits() throws Exception {
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
    DecimalFormat df = new DecimalFormat("#.#", dfs);
    df.setMaximumIntegerDigits(400);
    df.setGroupingUsed(false);

    df.setMaximumFractionDigits(0);
    assertEquals("1000000000000000", df.format(999999999999999.9));
    df.setMaximumFractionDigits(1);
    assertEquals("100000000000000", df.format(99999999999999.99));
    df.setMaximumFractionDigits(2);
    assertEquals("10000000000000", df.format(9999999999999.999));
    df.setMaximumFractionDigits(3);
    assertEquals("1000000000000", df.format(999999999999.9999));
    df.setMaximumFractionDigits(4);
    assertEquals("100000000000", df.format(99999999999.99999));
    df.setMaximumFractionDigits(5);
    assertEquals("10000000000", df.format(9999999999.999999));
    df.setMaximumFractionDigits(6);
    assertEquals("1000000000", df.format(999999999.9999999));
    df.setMaximumFractionDigits(7);
    assertEquals("100000000", df.format(99999999.99999999));
    df.setMaximumFractionDigits(8);
    assertEquals("10000000", df.format(9999999.999999999));
    df.setMaximumFractionDigits(9);
    assertEquals("1000000", df.format(999999.9999999999));
    df.setMaximumFractionDigits(10);
    assertEquals("100000", df.format(99999.99999999999));
    df.setMaximumFractionDigits(11);
    assertEquals("10000", df.format(9999.999999999999));
    df.setMaximumFractionDigits(12);
    assertEquals("1000", df.format(999.9999999999999));
    df.setMaximumFractionDigits(13);
    assertEquals("100", df.format(99.99999999999999));
    df.setMaximumFractionDigits(14);
    assertEquals("10", df.format(9.999999999999999));
    df.setMaximumFractionDigits(15);
    assertEquals("1", df.format(0.9999999999999999));
}
 
Example 11
Source File: MatrixD.java    From chart-fx 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(final PrintWriter output, final int w, final int d) {
    final 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 12
Source File: ImagePanel.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    VolatileImage ri = this.renderImage;
    if (ri != null) {
        calcRect();
        if (ri.validate(View.getDefaultConfiguration()) != VolatileImage.IMAGE_OK) {
            ri = View.createRenderImage(getWidth(), getHeight(), Transparency.TRANSLUCENT);
            render();
        }

        if (ri != null) {
            g2d.drawImage(ri, 0, 0, null);
        }
    }
    g2d.setColor(Color.red);

    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(0);
    df.setGroupingUsed(false);

    float frameLoss = 100 - (getFpsIs() / fpsShouldBe * 100);

    if (Configuration._debugMode.get()) {
        g2d.drawString("frameLoss:" + df.format(frameLoss) + "%", 20, 20);
    }
}
 
Example 13
Source File: Matrix.java    From KEEL with GNU 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      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 14
Source File: DurationParameterValidator.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Taken from org.oscm.ui.common.DurationValidation
 * 
 * @param valueToCheck
 * @return
 */
private Number getParsedDuration(String valueToCheck) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.getDefault());
    DecimalFormat df = new DecimalFormat(DURATION_FORMAT, dfs);
    df.setGroupingUsed(true);
    try {
        return df.parse(valueToCheck);
    } catch (ParseException e) {
        return null;
    }
}
 
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: Komi.java    From FancyBing with GNU General Public License v3.0 5 votes vote down vote up
public String toString()
{
    DecimalFormat format =
        (DecimalFormat)(NumberFormat.getInstance(Locale.ENGLISH));
    format.setGroupingUsed(false);
    format.setDecimalSeparatorAlwaysShown(false);
    return format.format(m_value);
}
 
Example 17
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_formatDouble_maxFractionDigits() {
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
    DecimalFormat format = new DecimalFormat("#0.#", dfs);
    format.setGroupingUsed(false);
    format.setMaximumIntegerDigits(400);
    format.setMaximumFractionDigits(1);

    assertEquals("1", format.format(0.99));
    assertEquals("1", format.format(0.95));
    assertEquals("0.9", format.format(0.94));
    assertEquals("0.9", format.format(0.90));

    assertEquals("0.2", format.format(0.19));
    assertEquals("0.2", format.format(0.15));
    assertEquals("0.1", format.format(0.14));
    assertEquals("0.1", format.format(0.10));

    format.setMaximumFractionDigits(10);
    assertEquals("1", format.format(0.99999999999));
    assertEquals("1", format.format(0.99999999995));
    assertEquals("0.9999999999", format.format(0.99999999994));
    assertEquals("0.9999999999", format.format(0.99999999990));

    assertEquals("0.1111111112", format.format(0.11111111119));
    assertEquals("0.1111111112", format.format(0.11111111115));
    assertEquals("0.1111111111", format.format(0.11111111114));
    assertEquals("0.1111111111", format.format(0.11111111110));

    format.setMaximumFractionDigits(14);
    assertEquals("1", format.format(0.999999999999999));
    assertEquals("1", format.format(0.999999999999995));
    assertEquals("0.99999999999999", format.format(0.999999999999994));
    assertEquals("0.99999999999999", format.format(0.999999999999990));

    assertEquals("0.11111111111112", format.format(0.111111111111119));
    assertEquals("0.11111111111112", format.format(0.111111111111115));
    assertEquals("0.11111111111111", format.format(0.111111111111114));
    assertEquals("0.11111111111111", format.format(0.111111111111110));
}
 
Example 18
Source File: Matrix.java    From tsml with GNU 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      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 19
Source File: NumberFormatter.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * initializes numeric format pattern
 * 
 * @param patternStr
 *            ths string used for formatting numeric data
 */
public void applyPattern( String patternStr )
{
	try
	{
		patternStr = processPatternAttributes( patternStr );
		this.formatPattern = patternStr;
		hexFlag = false;
		roundPrecision = -1;
		realPattern = formatPattern;

		// null format String
		if ( this.formatPattern == null )
		{
			numberFormat = NumberFormat.getInstance( locale.toLocale( ) );
			numberFormat.setGroupingUsed( false );
			DecimalFormatSymbols symbols = new DecimalFormatSymbols( locale
					.toLocale( ) );
			decimalSeparator = symbols.getDecimalSeparator( );
			decimalFormat = new DecimalFormat( "", //$NON-NLS-1$
					new DecimalFormatSymbols( locale.toLocale( ) ) );
			decimalFormat.setMinimumIntegerDigits( 1 );
			decimalFormat.setGroupingUsed( false );
			roundPrecision = getRoundPrecision( numberFormat );
			applyPatternAttributes( );
			return;
		}

		// Single character format string
		if ( patternStr.length( ) == 1 )
		{
			handleSingleCharFormatString( patternStr.charAt( 0 ) );
			roundPrecision = getRoundPrecision( numberFormat );
			applyPatternAttributes( );
			return;
		}

		// Named formats and arbitrary format string
		handleNamedFormats( patternStr );
		roundPrecision = getRoundPrecision( numberFormat );
		applyPatternAttributes( );
	}
	catch ( Exception illeagueE )
	{
		logger.log( Level.WARNING, illeagueE.getMessage( ), illeagueE );
	}
}
 
Example 20
Source File: GradebookServiceHibernateImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public String getAssignmentScoreString(final String gradebookUid, final Long assignmentId, final String studentUid)
		throws GradebookNotFoundException, AssessmentNotFoundException {
	final boolean studentRequestingOwnScore = this.authn.getUserUid().equals(studentUid);

	if (gradebookUid == null || assignmentId == null || studentUid == null) {
		throw new IllegalArgumentException("null parameter passed to getAssignment. Values are gradebookUid:"
				+ gradebookUid + " assignmentId:" + assignmentId + " studentUid:" + studentUid);
	}

	final Double assignmentScore = (Double) getHibernateTemplate().execute(new HibernateCallback() {
		@Override
		public Object doInHibernate(final Session session) throws HibernateException {
			final GradebookAssignment assignment = getAssignmentWithoutStats(gradebookUid, assignmentId);
			if (assignment == null) {
				throw new AssessmentNotFoundException(
						"There is no assignment with id " + assignmentId + " in gradebook " + gradebookUid);
			}

			if (!studentRequestingOwnScore && !isUserAbleToViewItemForStudent(gradebookUid, assignmentId, studentUid)) {
				log.error("AUTHORIZATION FAILURE: User {} in gradebook {} attempted to retrieve grade for student {} for assignment {}",
						getUserUid(), gradebookUid, studentUid, assignment.getName());
				throw new GradebookSecurityException();
			}

			// If this is the student, then the assignment needs to have
			// been released.
			if (studentRequestingOwnScore && !assignment.isReleased()) {
				log.error("AUTHORIZATION FAILURE: Student {} in gradebook {} attempted to retrieve score for unreleased assignment {}",
						getUserUid(), gradebookUid, assignment.getName());
				throw new GradebookSecurityException();
			}

			final AssignmentGradeRecord gradeRecord = getAssignmentGradeRecord(assignment, studentUid);
			if (log.isDebugEnabled()) {
				log.debug("gradeRecord=" + gradeRecord);
			}
			if (gradeRecord == null) {
				return null;
			} else {
				return gradeRecord.getPointsEarned();
			}
		}
	});
	if (log.isDebugEnabled()) {
		log.debug("returning " + assignmentScore);
	}

	// TODO: when ungraded items is considered, change column to ungraded-grade
	// its possible that the assignment score is null
	if (assignmentScore == null) {
		return null;
	}

	// avoid scientific notation on large scores by using a formatter
	final NumberFormat numberFormat = NumberFormat.getInstance(new ResourceLoader().getLocale());
	final DecimalFormat df = (DecimalFormat) numberFormat;
	df.setGroupingUsed(false);

	return df.format(assignmentScore);
}