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

The following examples show how to use java.text.DecimalFormat#setDecimalFormatSymbols() . 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: NonBlockingStatsDClient.java    From java-dogstatsd-client with MIT License 6 votes vote down vote up
private static NumberFormat newFormatter(boolean sampler) {
    // Always create the formatter for the US locale in order to avoid this bug:
    // https://github.com/indeedeng/java-dogstatsd-client/issues/3
    NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
    numberFormatter.setGroupingUsed(false);

    // we need to specify a value for Double.NaN that is recognized by dogStatsD
    if (numberFormatter instanceof DecimalFormat) { // better safe than a runtime error
        final DecimalFormat decimalFormat = (DecimalFormat) numberFormatter;
        final DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
        symbols.setNaN("NaN");
        decimalFormat.setDecimalFormatSymbols(symbols);
    }

    if (sampler) {
        numberFormatter.setMinimumFractionDigits(6);
    } else {
        numberFormatter.setMaximumFractionDigits(6);
    }

    return numberFormatter;
}
 
Example 2
Source File: AmountEditor.java    From fingen with Apache License 2.0 6 votes vote down vote up
public BigDecimal getAmount() {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator(' ');
    DecimalFormat df = new DecimalFormat("#,###.##");
    df.setDecimalSeparatorAlwaysShown(true);
    df.setDecimalFormatSymbols(symbols);
    df.setParseBigDecimal(true);
    try {
        String s = edAmount.getText().toString();
        if (s.equals("")) {
            s = "0";
        }
        return ((BigDecimal) df.parse(s.replaceAll(" ", ""))).setScale(2, RoundingMode.HALF_UP);
    } catch (NumberFormatException | ParseException nfe) {
        return BigDecimal.ZERO;
    }
}
 
Example 3
Source File: DecimalFormatter.java    From ncalc with GNU General Public License v3.0 6 votes vote down vote up
public static String round(String value, int places) {
    try {
        String pattern = "0.";
        if (places == 0) pattern += "#";
        else {
            for (int i = 0; i < places; i++) {
                pattern += "#";
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        decimalFormat.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
        return decimalFormat.format(new BigDecimal(value));
    } catch (Exception e) { //complex number
        return value;
    }
}
 
Example 4
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 5
Source File: ExecutionTimeFormatter.java    From quickperf with Apache License 2.0 5 votes vote down vote up
private DecimalFormat buildFormatWithSpaceGroupingSeparator() {
    DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH);
    DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    decimalFormat.setDecimalFormatSymbols(symbols);
    return decimalFormat;
}
 
Example 6
Source File: NumberTextWatcher.java    From fingen with Apache License 2.0 5 votes vote down vote up
public NumberTextWatcher(EditText et, TextWatcher textWatcher) {
    mTextWatcher = textWatcher;
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator(' ');
    df = new DecimalFormat("#,###.##");
    df.setDecimalSeparatorAlwaysShown(true);
    df.setDecimalFormatSymbols(symbols);
    dfnd = new DecimalFormat("#,###");
    dfnd.setDecimalFormatSymbols(symbols);
    this.et = et;
    hasFractionalPart = false;
}
 
Example 7
Source File: Budget.java    From rally with Apache License 2.0 5 votes vote down vote up
public Budget(String name, float currAmount, float limitAmount, int color) {
    mName = name;
    mCurrAmount = currAmount;
    mLimitAmount = limitAmount;
    mColor = color;

    mFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols symbols = mFormatter.getDecimalFormatSymbols();
    symbols.setCurrencySymbol("");
    mFormatter.setDecimalFormatSymbols(symbols);
    mCurrencyFormatter = NumberFormat.getCurrencyInstance();
}
 
Example 8
Source File: AbstractTranslet.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Adds a DecimalFormat object to the _formatSymbols map.
 * The entry is created with the input DecimalFormatSymbols.
 */
public void addDecimalFormat(String name, DecimalFormatSymbols symbols) {
    // Instanciate map for formatting symbols if needed
    if (_formatSymbols == null) _formatSymbols = new HashMap<>();

    // The name cannot be null - use empty string instead
    if (name == null) name = EMPTYSTRING;

    // Construct a DecimalFormat object containing the symbols we got
    final DecimalFormat df = new DecimalFormat();
    if (symbols != null) {
        df.setDecimalFormatSymbols(symbols);
    }
    _formatSymbols.put(name, df);
}
 
Example 9
Source File: AssessmentGradingFacadeQueries.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Double getAverageSubmittedAssessmentGrading(final Long publishedAssessmentId, final String agentId) {
    Double averageScore = 0.0;
    AssessmentGradingData ag = null;

    final HibernateCallback<List<AssessmentGradingData>> hcb = session -> {
        Query q = session.createQuery(
                "from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by  a.submittedDate desc");
        q.setLong("id", publishedAssessmentId);
        q.setString("agent", agentId);
        q.setBoolean("forgrade", true);
        q.setInteger("status", AssessmentGradingData.REMOVED);
        return q.list();
    };
    List<AssessmentGradingData> assessmentGradings = getHibernateTemplate().execute(hcb);

    if (!assessmentGradings.isEmpty()) {
        AssessmentGradingData agd;
        Double cumulativeScore = new Double(0);
        Iterator i = assessmentGradings.iterator();

        while (i.hasNext()) {
            agd = (AssessmentGradingData) i.next();
            cumulativeScore += agd.getFinalScore();
        }
        averageScore = cumulativeScore / assessmentGradings.size();

        DecimalFormat df = new DecimalFormat("0.##");
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setDecimalSeparator('.');
        df.setDecimalFormatSymbols(dfs);

        averageScore = new Double(df.format((double) averageScore));
    }
    return averageScore;
}
 
Example 10
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 11
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_equals() {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    DecimalFormat cloned = (DecimalFormat) format.clone();
    cloned.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    assertEquals(format, cloned);

    Currency c = Currency.getInstance(Locale.US);
    cloned.setCurrency(c);

    assertEquals(format, cloned);
}
 
Example 12
Source File: DecimalFormatUtil.java    From RxAndroidBootstrap with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a thousans separated decimar formatter.
 *
 * @return
 */
public static DecimalFormat getThousandSeperatedDecimalFormat() {
    DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    df.setDecimalFormatSymbols(symbols);
    return df;
}
 
Example 13
Source File: CurrenciesUtil.java    From px-android with MIT License 5 votes vote down vote up
public static String getLocalizedAmountNoDecimals(final BigDecimal truncated, final Currency currency) {
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator(currency.getDecimalSeparator());
    dfs.setGroupingSeparator(currency.getThousandsSeparator());
    final DecimalFormat df = new DecimalFormat();
    df.setDecimalFormatSymbols(dfs);
    df.setMinimumFractionDigits(0);
    df.setMaximumFractionDigits(0);
    return df.format(truncated);
}
 
Example 14
Source File: Bill.java    From rally with Apache License 2.0 5 votes vote down vote up
public Bill(String name, float amount, Date dueDate, int color) {
    mName = name;
    mAmount = amount;
    mDueDate = dueDate;
    mColor = color;

    mFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols symbols = mFormatter.getDecimalFormatSymbols();
    symbols.setCurrencySymbol("");
    mFormatter.setDecimalFormatSymbols(symbols);
}
 
Example 15
Source File: AbstractTranslet.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a DecimalFormat object to the _formatSymbols map.
 * The entry is created with the input DecimalFormatSymbols.
 */
public void addDecimalFormat(String name, DecimalFormatSymbols symbols) {
    // Instanciate map for formatting symbols if needed
    if (_formatSymbols == null) _formatSymbols = new HashMap<>();

    // The name cannot be null - use empty string instead
    if (name == null) name = EMPTYSTRING;

    // Construct a DecimalFormat object containing the symbols we got
    final DecimalFormat df = new DecimalFormat();
    if (symbols != null) {
        df.setDecimalFormatSymbols(symbols);
    }
    _formatSymbols.put(name, df);
}
 
Example 16
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 17
Source File: AdministrativeStaff.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
protected DecimalFormat format() {
	DecimalFormat df = new DecimalFormat();
	df.setMaximumFractionDigits(3);
	df.setMinimumFractionDigits(3);
	DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
	dfs.setDecimalSeparator((new String(".").charAt(0)));
	df.setDecimalFormatSymbols(dfs);
	df.setGroupingSize(20);
	return df;

}
 
Example 18
Source File: StringUtil.java    From hop with Apache License 2.0 4 votes vote down vote up
public static double str2num( String pattern, String decimal, String grouping, String currency, String value ) throws HopValueException {
  // 0 : pattern
  // 1 : Decimal separator
  // 2 : Grouping separator
  // 3 : Currency symbol

  NumberFormat nf = NumberFormat.getInstance();
  DecimalFormat df = (DecimalFormat) nf;
  DecimalFormatSymbols dfs = new DecimalFormatSymbols();

  if ( !Utils.isEmpty( pattern ) ) {
    df.applyPattern( pattern );
  }
  if ( !Utils.isEmpty( decimal ) ) {
    dfs.setDecimalSeparator( decimal.charAt( 0 ) );
  }
  if ( !Utils.isEmpty( grouping ) ) {
    dfs.setGroupingSeparator( grouping.charAt( 0 ) );
  }
  if ( !Utils.isEmpty( currency ) ) {
    dfs.setCurrencySymbol( currency );
  }
  try {
    df.setDecimalFormatSymbols( dfs );
    return df.parse( value ).doubleValue();
  } catch ( Exception e ) {
    String message = "Couldn't convert string to number " + e.toString();
    if ( !isEmpty( pattern ) ) {
      message += " pattern=" + pattern;
    }
    if ( !isEmpty( decimal ) ) {
      message += " decimal=" + decimal;
    }
    if ( !isEmpty( grouping ) ) {
      message += " grouping=" + grouping.charAt( 0 );
    }
    if ( !isEmpty( currency ) ) {
      message += " currency=" + currency;
    }
    throw new HopValueException( message );
  }
}
 
Example 19
Source File: BenchmarkUtil.java    From Dali with Apache License 2.0 4 votes vote down vote up
public static String formatNum(double number, String formatString) {
    final DecimalFormat format = new DecimalFormat(formatString);
    format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    format.setRoundingMode(RoundingMode.HALF_UP);
    return format.format(number);
}
 
Example 20
Source File: WmsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Build the base part of the url (doesn't change for getMap or getFeatureInfo requests).
 * 
 * @param targetUrl
 *            base url
 * @param width
 *            image width
 * @param height
 *            image height
 * @param box
 *            bounding box
 * @return base WMS url
 * @throws GeomajasException
 *             missing parameter
 */
private StringBuilder formatBaseUrl(String targetUrl, int width, int height, Bbox box) throws GeomajasException {
	try {
		StringBuilder url = new StringBuilder(targetUrl);
		int pos = url.lastIndexOf("?");
		if (pos > 0) {
			url.append("&SERVICE=WMS");
		} else {
			url.append("?SERVICE=WMS");
		}
		String layers = getId();
		if (layerInfo.getDataSourceName() != null) {
			layers = layerInfo.getDataSourceName();
		}
		url.append("&layers=");
		url.append(URLEncoder.encode(layers, "UTF8"));
		url.append("&WIDTH=");
		url.append(Integer.toString(width));
		url.append("&HEIGHT=");
		url.append(Integer.toString(height));
		DecimalFormat decimalFormat = new DecimalFormat(); // create new as this is not thread safe
		decimalFormat.setDecimalSeparatorAlwaysShown(false);
		decimalFormat.setGroupingUsed(false);
		decimalFormat.setMinimumFractionDigits(0);
		decimalFormat.setMaximumFractionDigits(100);
		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
		symbols.setDecimalSeparator('.');
		decimalFormat.setDecimalFormatSymbols(symbols);

		url.append("&bbox=");
		url.append(decimalFormat.format(box.getX()));
		url.append(",");
		url.append(decimalFormat.format(box.getY()));
		url.append(",");
		url.append(decimalFormat.format(box.getMaxX()));
		url.append(",");
		url.append(decimalFormat.format(box.getMaxY()));
		url.append("&format=");
		url.append(format);
		url.append("&version=");
		url.append(version);
		if ("1.3.0".equals(version)) {
			url.append("&crs=");
		} else {
			url.append("&srs=");
		}
		url.append(URLEncoder.encode(layerInfo.getCrs(), "UTF8"));
		url.append("&styles=");
		url.append(styles);
		if (null != parameters) {
			for (Parameter p : parameters) {
				url.append("&");
				url.append(URLEncoder.encode(p.getName(), "UTF8"));
				url.append("=");
				url.append(URLEncoder.encode(p.getValue(), "UTF8"));
			}
		}
		if (useProxy && null != securityContext.getToken()) {
			url.append("&userToken=");
			url.append(securityContext.getToken());
		}
		return url;
	} catch (UnsupportedEncodingException uee) {
		throw new IllegalStateException("Cannot find UTF8 encoding?", uee);
	}
}