List of usage examples for java.text NumberFormat getNumberInstance
public static NumberFormat getNumberInstance(Locale inLocale)
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
public BigDecimal convertFrom(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();//w w w . ja va 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 { BigDecimal number = null; if (StringUtils.isNotBlank(numericalValueFormatted)) { String source = numericalValueFormatted.trim(); final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); final DecimalFormat df = (DecimalFormat) format; final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); // 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 NumberFormatter numberFormatter = new NumberFormatter(); final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); if (parsedNumber instanceof BigDecimal) { number = (BigDecimal) parsedNumber; } else { number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); } } return number; } catch (final ParseException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.invalid.decimal.format", "The parameter " + parameterName + " has value: " + numericalValueFormatted + " which is invalid decimal 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.orcid.frontend.web.controllers.FundingsController.java
/** * Transforms a string into a BigDecimal * //from w ww. java 2 s .c o m * @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.rythmengine.utils.S.java
/** * Format the number with specified template, pattern, language and locale * @param number/* www. j ava2s .c o m*/ * @param pattern * @param locale * @return the formatted String * @see DecimalFormatSymbols */ public static String format(ITemplate template, Number number, String pattern, Locale locale) { if (null == number) number = 0; if (null == locale) { locale = I18N.locale(template); } NumberFormat nf; if (null == pattern) nf = NumberFormat.getNumberInstance(locale); else { DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); nf = new DecimalFormat(pattern, symbols); } return nf.format(number); }
From source file:org.orcid.frontend.web.controllers.FundingsController.java
/** * Get a string with the proper amount format * /*from w ww . j a va2 s .c o m*/ * @param local * @return an example string showing how the amount should be entered * */ private String getSampleAmountInProperFormat(Locale locale) { double example = 1234567.89; NumberFormat numberFormatExample = NumberFormat.getNumberInstance(locale); return numberFormatExample.format(example); }
From source file:org.orcid.frontend.web.controllers.FundingsController.java
/** * Format a big decimal based on a locale * //from w w w . j av a2s . co m * @param bigDecimal * @param currencyCode * @return a string with the number formatted based on the locale * */ private String formatAmountString(BigDecimal bigDecimal) { NumberFormat numberFormat = NumberFormat.getNumberInstance(localeManager.getLocale()); return numberFormat.format(bigDecimal); }
From source file:com.nuvolect.deepdive.probe.DecompileApk.java
private JSONObject dex2jar() { // DEX 2 JAR CONFIGS final boolean reuseReg = false; // reuse register while generate java .class file final boolean topologicalSort1 = false; // same with --topological-sort/-ts final boolean topologicalSort = false; // sort block by topological, that will generate more readable code final boolean verbose = true; // show progress final boolean debugInfo = false; // translate debug info final boolean printIR = false; // print ir to System.out final boolean optimizeSynchronized = true; // Optimise-synchronised final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override/*from ww w .jav a 2s .c om*/ public void uncaughtException(Thread t, Throwable e) { LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString()); m_progressStream.putStream("Uncaught exception: " + t.getName()); m_progressStream.putStream("Uncaught exception: " + e.toString()); } }; m_dex2jar_time = System.currentTimeMillis(); // Save start time for tracking m_dex2jarThread = new Thread(m_threadGroup, new Runnable() { @Override public void run() { boolean success = false; OmniFile dexFile = null; OmniFile jarFile = null; m_progressStream.putStream("DEX to JAR starting"); for (String fileName : m_dexFileNames) { dexFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".dex"); if (dexFile.exists() && dexFile.isFile()) { String size = NumberFormat.getNumberInstance(Locale.US).format(dexFile.length()); m_progressStream.putStream("DEX to JAR processing: " + dexFile.getName() + ", " + size); DexExceptionHandlerMod dexExceptionHandlerMod = new DexExceptionHandlerMod(); jarFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".jar"); if (jarFile.exists()) jarFile.delete(); try { DexFileReader reader = new DexFileReader(dexFile.getStdFile()); Dex2jar dex2jar = Dex2jar.from(reader).reUseReg(reuseReg) .topoLogicalSort(topologicalSort || topologicalSort1).skipDebug(!debugInfo) .optimizeSynchronized(optimizeSynchronized).printIR(printIR); //.verbose(verbose); dex2jar.setExceptionHandler(dexExceptionHandlerMod); dex2jar.to(jarFile.getStdFile()); success = true; } catch (Exception e) { String ex = LogUtil.logException(LogUtil.LogType.DECOMPILE, e); m_progressStream.putStream(ex); m_progressStream.putStream("DEX to JAR failed: " + jarFile.getName()); success = false; continue; } if (success) { size = NumberFormat.getNumberInstance(Locale.US).format(jarFile.length()); m_progressStream.putStream("DEX to JAR succeeded: " + jarFile.getName() + ", " + size); } else { m_progressStream .putStream("Exception thrown, file cannot be decompiled: " + dexFile.getPath()); } } } if (jarFile == null) m_progressStream.putStream("No DEX file found: " + m_dexFileNames); m_progressStream.putStream("DEX to JAR complete: " + TimeUtil.deltaTimeHrMinSec(m_dex2jar_time)); m_dex2jar_time = 0; } }, DEX2JAR_THREAD, STACK_SIZE); m_dex2jarThread.setPriority(Thread.MAX_PRIORITY); m_dex2jarThread.setUncaughtExceptionHandler(uncaughtExceptionHandler); m_dex2jarThread.start(); JSONObject wrapper = new JSONObject(); try { wrapper.put("dex2jar_thread", getThreadStatus(true, m_dex2jarThread)); } catch (JSONException e) { LogUtil.logException(LogUtil.LogType.DECOMPILE, e); } return wrapper; }
From source file:org.openmrs.Obs.java
/** * Convenience method for obtaining the observation's value as a string If the Obs is complex, * returns the title of the complexData denoted by the section of getValueComplex() before the * first bar '|' character; or returns the entire getValueComplex() if the bar '|' character is * missing./* w ww . ja v a2s . c o m*/ * * @param locale locale for locale-specific depictions of value * @should return first part of valueComplex for complex obs * @should return first part of valueComplex for non null valueComplexes * @should return non precise values for NumericConcepts * @should return date in correct format * @should not return long decimal numbers as scientific notation * @should use commas or decimal places depending on locale * @should not use thousand separator * @should return regular number for size of zero to or greater than ten digits * @should return regular number if decimal places are as high as six */ public String getValueAsString(Locale locale) { // formatting for the return of numbers of type double NumberFormat nf = NumberFormat.getNumberInstance(locale); DecimalFormat df = (DecimalFormat) nf; df.applyPattern("#0.0#####"); // formatting style up to 6 digits //branch on hl7 abbreviations if (getConcept() != null) { String abbrev = getConcept().getDatatype().getHl7Abbreviation(); if ("BIT".equals(abbrev)) { return getValueAsBoolean() == null ? "" : getValueAsBoolean().toString(); } else if ("CWE".equals(abbrev)) { if (getValueCoded() == null) { return ""; } if (getValueDrug() != null) { return getValueDrug().getFullName(locale); } else { ConceptName valueCodedName = getValueCodedName(); if (valueCodedName != null) { return getValueCoded().getName(locale, false).getName(); } else { ConceptName fallbackName = getValueCoded().getName(); if (fallbackName != null) { return fallbackName.getName(); } else { return ""; } } } } else if ("NM".equals(abbrev) || "SN".equals(abbrev)) { if (getValueNumeric() == null) { return ""; } else { if (getConcept() instanceof ConceptNumeric) { ConceptNumeric cn = (ConceptNumeric) getConcept(); if (!cn.isPrecise()) { double d = getValueNumeric(); int i = (int) d; return Integer.toString(i); } else { df.format(getValueNumeric()); } } } } else if ("DT".equals(abbrev)) { DateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN); return (getValueDatetime() == null ? "" : dateFormat.format(getValueDatetime())); } else if ("TM".equals(abbrev)) { return (getValueDatetime() == null ? "" : Format.format(getValueDatetime(), locale, FORMAT_TYPE.TIME)); } else if ("TS".equals(abbrev)) { return (getValueDatetime() == null ? "" : Format.format(getValueDatetime(), locale, FORMAT_TYPE.TIMESTAMP)); } else if ("ST".equals(abbrev)) { return getValueText(); } else if ("ED".equals(abbrev) && getValueComplex() != null) { String[] valueComplex = getValueComplex().split("\\|"); for (int i = 0; i < valueComplex.length; i++) { if (StringUtils.isNotEmpty(valueComplex[i])) { return valueComplex[i].trim(); } } } } // if the datatype is 'unknown', default to just returning what is not null if (getValueNumeric() != null) { return df.format(getValueNumeric()); } else if (getValueCoded() != null) { if (getValueDrug() != null) { return getValueDrug().getFullName(locale); } else { ConceptName valudeCodedName = getValueCodedName(); if (valudeCodedName != null) { return valudeCodedName.getName(); } else { return ""; } } } else if (getValueDatetime() != null) { return Format.format(getValueDatetime(), locale, FORMAT_TYPE.DATE); } else if (getValueText() != null) { return getValueText(); } else if (hasGroupMembers()) { // all of the values are null and we're an obs group...so loop // over the members and just do a getValueAsString on those // this could potentially cause an infinite loop if an obs group // is a member of its own group at some point in the hierarchy StringBuilder sb = new StringBuilder(); for (Obs groupMember : getGroupMembers()) { if (sb.length() > 0) { sb.append(", "); } sb.append(groupMember.getValueAsString(locale)); } return sb.toString(); } // returns the title portion of the valueComplex // which is everything before the first bar '|' character. if (getValueComplex() != null) { String[] valueComplex = getValueComplex().split("\\|"); for (int i = 0; i < valueComplex.length; i++) { if (StringUtils.isNotEmpty(valueComplex[i])) { return valueComplex[i].trim(); } } } return ""; }
From source file:net.sf.jasperreports.chartthemes.spring.EyeCandySixtiesChartTheme.java
@Override protected JFreeChart createThermometerChart() throws JRException { JRThermometerPlot jrPlot = (JRThermometerPlot) getPlot(); // Create the plot that will hold the thermometer. ThermometerPlot chartPlot = new ThermometerPlot((ValueDataset) getDataset()); ChartUtil chartUtil = ChartUtil.getInstance(getChartContext().getJasperReportsContext()); // setting localized range axis formatters chartPlot.getRangeAxis().setStandardTickUnits(chartUtil.createIntegerTickUnits(getLocale())); // Build a chart around this plot JFreeChart jfreeChart = new JFreeChart(evaluateTextExpression(getChart().getTitleExpression()), null, chartPlot, getChart().getShowLegend() == null ? false : getChart().getShowLegend()); // Set the generic options configureChart(jfreeChart, getPlot()); jfreeChart.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT); jfreeChart.setBorderVisible(false);/* w w w.jav a2 s . c o m*/ Range range = convertRange(jrPlot.getDataRange()); if (range != null) { // Set the boundary of the thermomoter chartPlot.setLowerBound(range.getLowerBound()); chartPlot.setUpperBound(range.getUpperBound()); } chartPlot.setGap(0); // Units can only be Fahrenheit, Celsius or none, so turn off for now. chartPlot.setUnits(ThermometerPlot.UNITS_NONE); // Set the color of the mercury. Only used when the value is outside of // any defined ranges. Paint paint = jrPlot.getMercuryColor(); if (paint != null) { chartPlot.setUseSubrangePaint(false); } else { //it has no effect, but is kept for backward compatibility reasons paint = ChartThemesConstants.EYE_CANDY_SIXTIES_GRADIENT_PAINTS.get(0); } chartPlot.setMercuryPaint(paint); chartPlot.setThermometerPaint(THERMOMETER_COLOR); chartPlot.setThermometerStroke(new BasicStroke(2f)); chartPlot.setOutlineVisible(false); chartPlot.setValueFont(chartPlot.getValueFont().deriveFont(Font.BOLD)); // localizing the default format, can be overridden by display.getMask() chartPlot.setValueFormat(NumberFormat.getNumberInstance(getLocale())); // Set the formatting of the value display JRValueDisplay display = jrPlot.getValueDisplay(); if (display != null) { if (display.getColor() != null) { chartPlot.setValuePaint(display.getColor()); } if (display.getMask() != null) { chartPlot.setValueFormat( new DecimalFormat(display.getMask(), DecimalFormatSymbols.getInstance(getLocale()))); } if (display.getFont() != null) { // chartPlot.setValueFont(JRFontUtil.getAwtFont(display.getFont()).deriveFont(Font.BOLD)); } } // Set the location of where the value is displayed ValueLocationEnum valueLocation = jrPlot.getValueLocationValue(); switch (valueLocation) { case NONE: chartPlot.setValueLocation(ThermometerPlot.NONE); break; case LEFT: chartPlot.setValueLocation(ThermometerPlot.LEFT); break; case RIGHT: chartPlot.setValueLocation(ThermometerPlot.RIGHT); break; case BULB: default: chartPlot.setValueLocation(ThermometerPlot.BULB); break; } // Define the three ranges range = convertRange(jrPlot.getLowRange()); if (range != null) { chartPlot.setSubrangeInfo(2, range.getLowerBound(), range.getUpperBound()); } range = convertRange(jrPlot.getMediumRange()); if (range != null) { chartPlot.setSubrangeInfo(1, range.getLowerBound(), range.getUpperBound()); } range = convertRange(jrPlot.getHighRange()); if (range != null) { chartPlot.setSubrangeInfo(0, range.getLowerBound(), range.getUpperBound()); } return jfreeChart; }
From source file:com.netflix.ice.processor.BillingFileProcessor.java
private void sendOndemandCostAlert() { if (ondemandThreshold == null || StringUtils.isEmpty(fromEmail) || StringUtils.isEmpty(alertEmails) || endMilli < lastAlertMillis() + AwsUtils.hourMillis * 24) return;/* w w w .j a v a2 s. c om*/ Map<Long, Map<Ec2InstanceReservationPrice.Key, Double>> ondemandCosts = getOndemandCosts( lastAlertMillis() + AwsUtils.hourMillis); Long maxHour = null; double maxTotal = ondemandThreshold; for (Long hour : ondemandCosts.keySet()) { double total = 0; for (Double value : ondemandCosts.get(hour).values()) total += value; if (total > maxTotal) { maxHour = hour; maxTotal = total; } } if (maxHour != null) { NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US); String subject = String.format("Alert: Ondemand cost per hour reached $%s at %s", numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour)); StringBuilder body = new StringBuilder(); body.append(String.format("Total ondemand cost $%s at %s:<br><br>", numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour))); TreeMap<Double, String> costs = Maps.newTreeMap(); for (Map.Entry<Ec2InstanceReservationPrice.Key, Double> entry : ondemandCosts.get(maxHour).entrySet()) { costs.put(entry.getValue(), entry.getKey().region + " " + entry.getKey().usageType + ": "); } for (Double cost : costs.descendingKeySet()) { if (cost > 0) body.append(costs.get(cost)).append("$" + numberFormat.format(cost)).append("<br>"); } body.append("<br>Please go to <a href=\"" + urlPrefix + "dashboard/reservation#usage_cost=cost&groupBy=UsageType&product=ec2_instance&operation=OndemandInstances\">Ice</a> for details."); SendEmailRequest request = new SendEmailRequest(); request.withSource(fromEmail); List<String> emails = Lists.newArrayList(alertEmails.split(",")); request.withDestination(new Destination(emails)); request.withMessage( new Message(new Content(subject), new Body().withHtml(new Content(body.toString())))); AmazonSimpleEmailServiceClient emailService = AwsUtils.getAmazonSimpleEmailServiceClient(); try { emailService.sendEmail(request); updateLastAlertMillis(endMilli); logger.info("updateLastAlertMillis " + endMilli); } catch (Exception e) { logger.error("Error in sending alert emails", e); } } }