List of usage examples for java.text DecimalFormat getDecimalFormatSymbols
public DecimalFormatSymbols getDecimalFormatSymbols()
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
public Integer convertToInteger(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { if (clientApplicationLocale == null) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final String defaultMessage = new StringBuilder( "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.") .toString();//from ww w.j av a 2 s .c om final ApiParameterError error = ApiParameterError .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } try { Integer number = null; if (StringUtils.isNotBlank(numericalValueFormatted)) { String source = numericalValueFormatted.trim(); final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale); final DecimalFormat df = (DecimalFormat) format; final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); df.setParseBigDecimal(true); // http://bugs.sun.com/view_bug.do?bug_id=4510618 final char groupingSeparator = symbols.getGroupingSeparator(); if (groupingSeparator == '\u00a0') { source = source.replaceAll(" ", Character.toString('\u00a0')); } final Number parsedNumber = df.parse(source); final double parsedNumberDouble = parsedNumber.doubleValue(); final int parsedNumberInteger = parsedNumber.intValue(); if (source.contains(Character.toString(symbols.getDecimalSeparator()))) { throw new ParseException(source, 0); } if (!Double.valueOf(parsedNumberDouble) .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) { throw new ParseException(source, 0); } number = parsedNumber.intValue(); } return number; } catch (final ParseException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.invalid.integer.format", "The parameter " + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer value for provided locale of [" + clientApplicationLocale.toString() + "].", parameterName, numericalValueFormatted, clientApplicationLocale); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } }
From source file:org.mozilla.gecko.GeckoAppShell.java
private static void putLocaleEnv() { GeckoAppShell.putenv("LANG=" + Locale.getDefault().toString()); NumberFormat nf = NumberFormat.getInstance(); if (nf instanceof DecimalFormat) { DecimalFormat df = (DecimalFormat) nf; DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); GeckoAppShell.putenv("LOCALE_DECIMAL_POINT=" + dfs.getDecimalSeparator()); GeckoAppShell.putenv("LOCALE_THOUSANDS_SEP=" + dfs.getGroupingSeparator()); GeckoAppShell.putenv("LOCALE_GROUPING=" + (char) df.getGroupingSize()); }//from ww w . j av a2 s. co m }
From source file:org.apache.cordova.core.Globalization.java
private JSONObject getCurrencyPattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {/*w ww . ja v a2s .c o m*/ //get ISO 4217 currency code String code = options.getJSONObject(0).getString(CURRENCYCODE); //uses java.text.DecimalFormat to format value DecimalFormat fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); //set currency format Currency currency = Currency.getInstance(code); fmt.setCurrency(currency); //return properties obj.put("pattern", fmt.toPattern()); obj.put("code", currency.getCurrencyCode()); obj.put("fraction", fmt.getMinimumFractionDigits()); obj.put("rounding", new Integer(0)); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); } }
From source file:org.sakaiproject.component.gradebook.GradebookExternalAssessmentServiceImpl.java
/** * * @param doubleAsString/*from w ww.j av a 2 s .co m*/ * @return a locale-aware Double value representation of the given String * @throws ParseException */ private Double convertStringToDouble(String doubleAsString) { Double scoreAsDouble = null; if (doubleAsString != null && !"".equals(doubleAsString)) { try { // check if grade uses a comma as separator because of number format and change to a comma y the external app sends a point as separator DecimalFormat dcformat = (DecimalFormat) getNumberFormat(); String decSeparator = dcformat.getDecimalFormatSymbols().getDecimalSeparator() + ""; if (",".equals(decSeparator)) { doubleAsString = doubleAsString.replace(".", ","); } Number numericScore = getNumberFormat().parse(doubleAsString.trim()); scoreAsDouble = numericScore.doubleValue(); } catch (ParseException e) { log.error(e); } } return scoreAsDouble; }
From source file:org.orcid.frontend.web.controllers.FundingsController.java
/** * Transforms a string into a BigDecimal * /*w w w .j a v a2s. c om*/ * @param amount * @param locale * @return a BigDecimal containing the given amount * @throws Exception * if the amount cannot be correctly parse into a BigDecimal * */ public BigDecimal getAmountAsBigDecimal(String amount, Locale locale) throws Exception { try { ParsePosition parsePosition = new ParsePosition(0); DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale); DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols(); /** * When spaces are allowed, the grouping separator is the character * 160, which is a non-breaking space So, lets change it so it uses * the default space as a separator * */ if (symbols.getGroupingSeparator() == 160) { symbols.setGroupingSeparator(' '); } numberFormat.setDecimalFormatSymbols(symbols); Number number = numberFormat.parse(amount, parsePosition); if (number == null || parsePosition.getIndex() != amount.length()) { throw new Exception(); } return new BigDecimal(number.toString()); } catch (Exception e) { throw e; } }
From source file:org.apache.cordova.globalization.Globalization.java
private JSONObject getCurrencyPattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {//from w w w . j a va 2s . c o m //get ISO 4217 currency code String code = options.getJSONObject(0).getString(CURRENCYCODE); //uses java.text.DecimalFormat to format value DecimalFormat fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); //set currency format Currency currency = Currency.getInstance(code); fmt.setCurrency(currency); //return properties obj.put("pattern", fmt.toPattern()); obj.put("code", currency.getCurrencyCode()); obj.put("fraction", fmt.getMinimumFractionDigits()); obj.put("rounding", Integer.valueOf(0)); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); } }
From source file:org.pentaho.di.core.util.StringEvaluator.java
private void populateConversionMetaList() { int[] trimTypes; if (tryTrimming) { trimTypes = new int[] { ValueMetaInterface.TRIM_TYPE_NONE, ValueMetaInterface.TRIM_TYPE_BOTH, }; } else {// w w w.ja va2 s. c o m trimTypes = new int[] { ValueMetaInterface.TRIM_TYPE_NONE, }; } for (int trimType : trimTypes) { for (String format : getDateFormats()) { ValueMetaInterface conversionMeta = new ValueMetaDate("date"); conversionMeta.setConversionMask(format); conversionMeta.setTrimType(trimType); conversionMeta.setDateFormatLenient(false); evaluationResults.add(new StringEvaluationResult(conversionMeta)); } EvalResultBuilder numberUsBuilder = new EvalResultBuilder("number-us", ValueMetaInterface.TYPE_NUMBER, 15, trimType, ".", ","); EvalResultBuilder numberEuBuilder = new EvalResultBuilder("number-eu", ValueMetaInterface.TYPE_NUMBER, 15, trimType, ",", "."); for (String format : getNumberFormats()) { if (format.equals("#") || format.equals("0")) { // skip the integer ones. we'll get those later continue; } int precision = determinePrecision(format); evaluationResults.add(numberUsBuilder.format(format, precision).build()); evaluationResults.add(numberEuBuilder.format(format, precision).build()); } // Try the locale's Currency DecimalFormat currencyFormat = ((DecimalFormat) NumberFormat.getCurrencyInstance()); ValueMetaInterface conversionMeta = new ValueMetaNumber("number-currency"); // replace the universal currency symbol with the locale's currency symbol for user recognition String currencyMask = currencyFormat.toLocalizedPattern().replace("\u00A4", currencyFormat.getCurrency().getSymbol()); conversionMeta.setConversionMask(currencyMask); conversionMeta.setTrimType(trimType); conversionMeta.setDecimalSymbol( String.valueOf(currencyFormat.getDecimalFormatSymbols().getDecimalSeparator())); conversionMeta.setGroupingSymbol( String.valueOf(currencyFormat.getDecimalFormatSymbols().getGroupingSeparator())); conversionMeta.setCurrencySymbol(currencyFormat.getCurrency().getSymbol()); conversionMeta.setLength(15); int currencyPrecision = currencyFormat.getCurrency().getDefaultFractionDigits(); conversionMeta.setPrecision(currencyPrecision); evaluationResults.add(new StringEvaluationResult(conversionMeta)); // add same mask w/o currency symbol String currencyMaskAsNumeric = currencyMask .replaceAll(Pattern.quote(currencyFormat.getCurrency().getSymbol()), ""); evaluationResults.add(numberUsBuilder.format(currencyMaskAsNumeric, currencyPrecision).build()); evaluationResults.add(numberEuBuilder.format(currencyMaskAsNumeric, currencyPrecision).build()); // Integer // conversionMeta = new ValueMetaInteger("integer"); conversionMeta.setConversionMask("#"); conversionMeta.setLength(15); evaluationResults.add(new StringEvaluationResult(conversionMeta)); conversionMeta = new ValueMetaInteger("integer"); conversionMeta.setConversionMask(" #"); conversionMeta.setLength(15); evaluationResults.add(new StringEvaluationResult(conversionMeta)); // Add support for left zero padded integers // for (int i = 1; i <= 15; i++) { String mask = " "; for (int x = 0; x < i; x++) { mask += "0"; } mask += ";-"; for (int x = 0; x < i; x++) { mask += "0"; } conversionMeta = new ValueMetaInteger("integer-zero-padded-" + i); conversionMeta.setConversionMask(mask); conversionMeta.setLength(i); evaluationResults.add(new StringEvaluationResult(conversionMeta)); } // Boolean // conversionMeta = new ValueMetaBoolean("boolean"); evaluationResults.add(new StringEvaluationResult(conversionMeta)); } }
From source file:com.flexive.shared.FxContext.java
/** * Get a number format instance depending on the current users formatting options * * @param locale locale to use// ww w .j a va 2 s .c o m * @return NumberFormat */ public NumberFormat getNumberFormatInstance(Locale locale) { final String currentUserKey = buildCurrentUserNumberFormatKey(); if (NUMBER_FORMATS.containsKey(locale)) { Map<String, NumberFormat> map = NUMBER_FORMATS.get(locale); if (map.containsKey(currentUserKey)) return map.get(currentUserKey); } else NUMBER_FORMATS.put(locale, new HashMap<String, NumberFormat>(5)); Map<String, NumberFormat> map = NUMBER_FORMATS.get(locale); DecimalFormat format = (DecimalFormat) DecimalFormat.getNumberInstance(locale); DecimalFormatSymbols dfs = (DecimalFormatSymbols) format.getDecimalFormatSymbols().clone(); dfs.setDecimalSeparator(getDecimalSeparator()); dfs.setGroupingSeparator(getGroupingSeparator()); format.setGroupingUsed(useGroupingSeparator()); format.setDecimalFormatSymbols(dfs); map.put(currentUserKey, format); return format; }
From source file:org.xwiki.batchimport.internal.DefaultBatchImport.java
public Map<String, Object> parseAndValidatePageData(Map<String, String> data, int rowIndex, List<String> currentLine, String fullName, BaseClass defaultClass, BatchImportConfiguration config, DateFormat defaultDateFormatter, NumberFormat numberFormatter, boolean simulation, BatchImportLog log, boolean forceReturnParsed) { Map<String, String> mapping = config.getFieldsMapping(); Character listSeparator = config.getListSeparator(); Map<String, Object> parsedData = new HashMap<String, Object>(); // TODO: use the simulation parameter to stop early in the verification, if it's not simulation to stop on first // error//from w w w . j av a 2 s. co m boolean hasValidationError = false; // now get all the fields in the data and check types and lengths for (Map.Entry<String, String> dataEntry : data.entrySet()) { String fieldName = dataEntry.getKey(); String column = mapping.get(fieldName); String value = dataEntry.getValue(); // this will be reassigned while validating formats, and added in the parsed data map at the end Object parsedValue = value; // skip empty columns -> put actual empty in the parsedData, so that we can distinguish null (== invalid) // from empty ( == empty string) if (StringUtils.isEmpty(value)) { parsedData.put(fieldName, ""); continue; } if (fieldName.startsWith("doc.")) { // no restrictions, only restrictions are about length for title, parent, if (fieldName.equals("doc.title")) { // limit at 255 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 255, log)) { hasValidationError = true; parsedValue = null; } } if (fieldName.equals("doc.parent")) { // limit at 511 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 511, log)) { hasValidationError = true; parsedValue = null; } } if (fieldName.equals("doc.content")) { // limit at 200000 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 200000, log)) { hasValidationError = true; parsedValue = null; } } // TODO: check doc.tags (but I don't know exactly how). For now, doc.tags is not even collected in the // data map, so we cannot check it here } else { // get the property from the class and validate it PropertyInterface prop = defaultClass.get(fieldName); if (prop instanceof StringClass && !(prop instanceof TextAreaClass)) { // check length, 255 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 255, log)) { hasValidationError = true; parsedValue = null; } } // textarea if (prop instanceof TextAreaClass) { // check length, 60 000 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 60000, log)) { hasValidationError = true; parsedValue = null; } } // we start checking types now and actually parsing string values to something else, depending on the // property type if (prop instanceof BooleanClass) { // this is a bit annoying for boolean, but let's make it, otherwise it might be too magic if (!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false") && !value.equalsIgnoreCase("0") && !value.equalsIgnoreCase("1")) { log.logError("errorvalidationtypeboolean", rowIndex, currentLine, fullName, fieldName, column, value); hasValidationError = true; parsedValue = null; } else { if (value.equalsIgnoreCase("1")) { parsedValue = Boolean.TRUE; } else { // this will be true only when the string is "true" so for both "0" and "false" it will be // false parsedValue = Boolean.parseBoolean(value); } } } if (prop instanceof NumberClass) { // we have 4 cases here, with type and length for each of them String ntype = ((NumberClass) prop).getNumberType(); String numberString = value; if (numberFormatter != null && numberFormatter instanceof DecimalFormat) { // There is a number formatter, so we need to clean a bit the value before parsing it, from a // locale pov. // Note: We tried NumberFormat#parse, but it's very complicated since number format can stop // earlier than the end of a string if it's encountering a character it doesn't know, so for // locale french it would stop on a dot (123.45 will return 123 as answer). We can know if it // stopped earlier, but then we need to check why and make sense of the rest (is it an error or // we're fine with the fact that it stopped earlier? e.g. in the case of a percent, 123,34%, // it's ok that it stops earlier, we like it). // So nicer solution here, we'll just take some common symbols from the locale and remove them // or replace them with the standard number separator (e.g. decimal point always goes to ., // thousands separator always goes to nothing, same for percent, same for currencies) and then // parse this as a standard number. DecimalFormat numberDecimalFormatter = (DecimalFormat) numberFormatter; // decimal separator turns into dot numberString = numberString.replaceAll(Pattern.quote( ((Character) numberDecimalFormatter.getDecimalFormatSymbols().getDecimalSeparator()) .toString()), "."); // thousands separator turns into nothing numberString = numberString.replaceAll(Pattern.quote(((Character) numberDecimalFormatter .getDecimalFormatSymbols().getGroupingSeparator()).toString()), ""); // currency turns into nothing numberString = numberString.replaceAll( Pattern.quote(numberDecimalFormatter.getDecimalFormatSymbols().getCurrencySymbol()), ""); numberString = numberString.replaceAll(Pattern.quote( numberDecimalFormatter.getDecimalFormatSymbols().getInternationalCurrencySymbol()), ""); // percent, per mill turn into nothing numberString = numberString.replaceAll(Pattern .quote(((Character) numberDecimalFormatter.getDecimalFormatSymbols().getPercent()) .toString()), ""); numberString = numberString.replaceAll(Pattern .quote(((Character) numberDecimalFormatter.getDecimalFormatSymbols().getPerMill()) .toString()), ""); // minus turns into minus numberString = numberString.replaceAll(Pattern .quote(((Character) numberDecimalFormatter.getDecimalFormatSymbols().getMinusSign()) .toString()), "-"); // and remove all other spaces that might be left numberString = numberString.trim(); } // I could use NumberClass#fromString, but it's logging as if one has introduced the value from // the UI, which I don't like. try { if (ntype.equals("integer")) { parsedValue = new Integer(numberString); } else if (ntype.equals("float")) { // FIXME: check that this constructor is not truncating when the value is too long parsedValue = new Float(numberString); } else if (ntype.equals("double")) { parsedValue = new Double(numberString); } else { parsedValue = new Long(numberString); } } catch (NumberFormatException nfe) { hasValidationError = true; parsedValue = null; log.logError("errorvalidationtype" + ntype, rowIndex, currentLine, fullName, fieldName, column, value); } // TODO: check some intervals, for some values which are available in java, but not in mysql (java // takes more than mysql, iirc) } if (prop instanceof DateClass) { debug("Found date " + value + " for key -" + fieldName + "-"); String datePropFormat = ((DateClass) prop).getDateFormat(); SimpleDateFormat sdf = new SimpleDateFormat(datePropFormat); try { parsedValue = sdf.parse(value); } catch (ParseException exc) { // try to parse with the default date then try { parsedValue = defaultDateFormatter.parse(value); } catch (ParseException e) { // now we cannot do much more hasValidationError = true; parsedValue = null; log.logError("errorvalidationtypedate", rowIndex, currentLine, fullName, fieldName, column, value, datePropFormat); debug("Failed to parse date " + value + " for key " + fieldName); } } } if (prop instanceof ListClass) { if (((ListClass) prop).isMultiSelect()) { List<String> listValues = getAsList(value, listSeparator); parsedValue = listValues; if (((ListClass) prop).isRelationalStorage()) { // check values one by one if they have appropriate length, namely 255 // NOTE that this 255 is not mentioned anywhere, it's the mysql reality (5.1), observed on // my machine, since there is no explicit information in the hibernate file for // xwikilistitems table for (String splitValue : listValues) { if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, splitValue, 255, log)) { hasValidationError = true; parsedValue = null; } } } else { // stored as StringListProperty, limit at 60 000 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 60000, log)) { hasValidationError = true; parsedValue = null; } } } else { // stored as StringProperty, limit at 255 if (!checkLength(rowIndex, currentLine, fullName, fieldName, column, value, 255, log)) { hasValidationError = true; parsedValue = null; } } } } // and finally put the data in the parsed data map parsedData.put(fieldName, parsedValue); } // if either we don't have validation error or we force the return of the parsed data, return the data, // otherwise null. if (!hasValidationError || forceReturnParsed) { return parsedData; } else { return null; } }
From source file:org.orcid.core.manager.impl.OrcidProfileManagerImpl.java
/** * Replace the funding amount string into the desired format * //from ww w.ja v a 2 s . c o m * @param updatedOrcidProfile * The profile containing the new funding * */ private void setFundingAmountsWithTheCorrectFormat(OrcidProfile updatedOrcidProfile) throws IllegalArgumentException { FundingList fundings = updatedOrcidProfile.retrieveFundings(); for (Funding funding : fundings.getFundings()) { // If the amount is not empty, update it if (funding.getAmount() != null && StringUtils.isNotBlank(funding.getAmount().getContent())) { String amount = funding.getAmount().getContent(); Locale locale = localeManager.getLocale(); ParsePosition parsePosition = new ParsePosition(0); DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale); DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols(); /** * When spaces are allowed, the grouping separator is the * character 160, which is a non-breaking space So, lets change * it so it uses the default space as a separator * */ if (symbols.getGroupingSeparator() == 160) { symbols.setGroupingSeparator(' '); } numberFormat.setDecimalFormatSymbols(symbols); Number number = numberFormat.parse(amount, parsePosition); String formattedAmount = number.toString(); if (parsePosition.getIndex() != amount.length()) { double example = 1234567.89; NumberFormat numberFormatExample = NumberFormat.getNumberInstance(localeManager.getLocale()); throw new IllegalArgumentException( "The amount: " + amount + " doesn'n have the right format, it should use the format: " + numberFormatExample.format(example)); } funding.getAmount().setContent(formattedAmount); } } }