Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getNumberInstance.

Prototype

public static NumberFormat getNumberInstance(Locale inLocale) 

Source Link

Document

Returns a general-purpose number format for the specified locale.

Usage

From source file:de.tynne.benchmarksuite.Main.java

private static String format(Args args, double number) throws IOException {
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
    nf.setGroupingUsed(false);/*  w  w w  .  j  a v  a 2  s  . co  m*/
    String string = nf.format(number);
    return string.replaceAll("\\.", args.getDecimalDot());
}

From source file:com.ryan.ryanreader.views.SubredditHeader.java

public SubredditHeader(final Context context, final RedditSubreddit subreddit) {

    super(context);

    final float dpScale = context.getResources().getDisplayMetrics().density;

    setOrientation(LinearLayout.VERTICAL);

    final int sidesPadding = (int) (15.0f * dpScale);
    final int topPadding = (int) (10.0f * dpScale);

    setPadding(sidesPadding, topPadding, sidesPadding, topPadding);

    final Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");

    final TextView title = new TextView(context);
    title.setTextSize(22.0f);//from   w w  w . j  av a 2 s . co m
    title.setTypeface(tf);
    title.setText(StringEscapeUtils.unescapeHtml4(subreddit.title));
    title.setTextColor(Color.WHITE);
    addView(title);

    final TextView subs = new TextView(context);
    subs.setTextSize(14.0f);

    if (subreddit.subscribers == null) {
        subs.setText("Subscriber count is unknown");
    } else {
        subs.setText(NumberFormat.getNumberInstance(Locale.getDefault()).format(subreddit.subscribers)
                + " subscribers");
    }

    subs.setTextColor(Color.rgb(200, 200, 200));
    addView(subs);

    setBackgroundColor(Color.rgb(50, 50, 50)); // TODO theme color
}

From source file:org.jboss.dashboard.displayer.chart.MeterChartDisplayerXMLFormat.java

protected void parseMeterProperties(DataDisplayer displayer, Node item, ImportResults results)
        throws Exception {
    Locale locale = LocaleManager.currentLocale();
    NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    MeterChartDisplayer meterDisplayer = (MeterChartDisplayer) displayer;
    if (item.getNodeName().equals("meter") && item.hasChildNodes()) {
        NodeList meterNodes = item.getChildNodes();
        for (int k = 0; k < meterNodes.getLength(); k++) {
            Node meterItem = meterNodes.item(k);
            if (meterItem.getNodeName().equals("positionType") && meterItem.hasChildNodes()) {
                meterDisplayer.setPositionType(
                        StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()));
            }//from w  w w . ja va  2s .c  o  m
            if (meterItem.getNodeName().equals("minValue") && meterItem.hasChildNodes()) {
                meterDisplayer.setMinValue(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (meterItem.getNodeName().equals("maxValue") && meterItem.hasChildNodes()) {
                meterDisplayer.setMaxValue(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (meterItem.getNodeName().equals("maxMeterTicks") && meterItem.hasChildNodes()) {
                meterDisplayer.setMaxMeterTicks(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()))
                        .intValue());
            }
            // Thresholds.
            if (meterItem.getNodeName().equals("warningThreshold") && meterItem.hasChildNodes()) {
                meterDisplayer.setWarningThreshold(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (meterItem.getNodeName().equals("criticalThreshold") && meterItem.hasChildNodes()) {
                meterDisplayer.setCriticalThreshold(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(meterItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            // Critical interval.
            if (meterItem.getNodeName().equals("descripCriticalInterval") && meterItem.hasChildNodes()) {
                String descripCriticalInterval = meterItem.getFirstChild().getNodeValue();
                Node languageNode = meterItem.getAttributes().getNamedItem("language");
                if (languageNode != null)
                    locale = new Locale(languageNode.getNodeValue());
                meterDisplayer.setDescripCriticalInterval(
                        StringEscapeUtils.unescapeXml(descripCriticalInterval), locale);
            }
            // Warning interval.
            if (meterItem.getNodeName().equals("descripWarningInterval") && meterItem.hasChildNodes()) {
                String descripWarningInterval = meterItem.getFirstChild().getNodeValue();
                Node languageNode = meterItem.getAttributes().getNamedItem("language");
                if (languageNode != null)
                    locale = new Locale(languageNode.getNodeValue());
                meterDisplayer.setDescripWarningInterval(StringEscapeUtils.unescapeXml(descripWarningInterval),
                        locale);
            }
            // Normal interval.
            if (meterItem.getNodeName().equals("descripNormalInterval") && meterItem.hasChildNodes()) {
                String descripNormalInterval = meterItem.getFirstChild().getNodeValue();
                Node languageNode = meterItem.getAttributes().getNamedItem("language");
                if (languageNode != null)
                    locale = new Locale(languageNode.getNodeValue());
                meterDisplayer.setDescripNormalInterval(StringEscapeUtils.unescapeXml(descripNormalInterval),
                        locale);
            }
        }
    } else if (item.getNodeName().equals("thermometer") && item.hasChildNodes()) {
        NodeList thermoNodes = item.getChildNodes();
        for (int k = 0; k < thermoNodes.getLength(); k++) {
            Node thermoItem = thermoNodes.item(k);
            if (thermoItem.getNodeName().equals("positionType") && thermoItem.hasChildNodes()) {
                meterDisplayer.setPositionType(
                        StringEscapeUtils.unescapeXml(thermoItem.getFirstChild().getNodeValue()));
            }
            if (thermoItem.getNodeName().equals("thermoLowerBound") && thermoItem.hasChildNodes()) {
                meterDisplayer.setThermoLowerBound(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(thermoItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (thermoItem.getNodeName().equals("thermoUpperBound") && thermoItem.hasChildNodes()) {
                meterDisplayer.setThermoUpperBound(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(thermoItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            // Thresholds.
            if (thermoItem.getNodeName().equals("warningThermoThreshold") && thermoItem.hasChildNodes()) {
                meterDisplayer.setWarningThermoThreshold(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(thermoItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (thermoItem.getNodeName().equals("criticalThermoThreshold") && thermoItem.hasChildNodes()) {
                meterDisplayer.setCriticalThermoThreshold(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(thermoItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
        }
    } else if (item.getNodeName().equals("dial")) {
        NodeList dialNodes = item.getChildNodes();
        for (int k = 0; k < dialNodes.getLength(); k++) {
            Node dialItem = dialNodes.item(k);
            if (dialItem.getNodeName().equals("positionType") && dialItem.hasChildNodes()) {
                meterDisplayer.setPositionType(
                        StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()));
            }
            if (dialItem.getNodeName().equals("pointerType") && dialItem.hasChildNodes()) {
                meterDisplayer
                        .setPointerType(StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()));
            }
            if (dialItem.getNodeName().equals("dialLowerBound") && dialItem.hasChildNodes()) {
                meterDisplayer.setDialLowerBound(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (dialItem.getNodeName().equals("dialUpperBound") && dialItem.hasChildNodes()) {
                meterDisplayer.setDialUpperBound(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()))
                        .doubleValue());
            }
            if (dialItem.getNodeName().equals("maxTicks") && dialItem.hasChildNodes()) {
                meterDisplayer.setMaxTicks(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()))
                        .intValue());
            }
            if (dialItem.getNodeName().equals("minorTickCount") && dialItem.hasChildNodes()) {
                meterDisplayer.setMinorTickCount(numberFormat
                        .parse(StringEscapeUtils.unescapeXml(dialItem.getFirstChild().getNodeValue()))
                        .intValue());
            }
        }
    }
}

From source file:org.projectforge.common.NumberHelper.java

public static NumberFormat getNumberFractionFormat(final Locale locale, final int fractionDigits) {
    final NumberFormat format = NumberFormat.getNumberInstance(locale);
    format.setMaximumFractionDigits(fractionDigits);
    format.setMinimumFractionDigits(fractionDigits);
    return format;
}

From source file:org.polymap.rhei.field.NumberValidator.java

/**
 * //w w  w  .ja  v a  2s . c om
 * @param maxIntegerDigits
 * @param maxFractionDigits
 * @param minIntegerDigits
 * @param minFractionDigits
 * @param locale The locale to use. Null indicates the the current default
 *        locale is to be used.
 */
public NumberValidator(Class<? extends Number> targetClass, Locale locale, int maxIntegerDigits,
        int maxFractionDigits, int minIntegerDigits, int minFractionDigits) {

    this.targetClass = targetClass;

    nf = locale != null ? NumberFormat.getNumberInstance(locale) : NumberFormat.getNumberInstance();
    nf.setMaximumIntegerDigits(maxIntegerDigits);
    nf.setMaximumFractionDigits(maxFractionDigits);
    nf.setMinimumIntegerDigits(minIntegerDigits);
    nf.setMinimumFractionDigits(minFractionDigits);
}

From source file:org.gluu.oxtrust.ldap.service.StatusCheckerTimer.java

@Create
public void create() {
    this.numberFormat = NumberFormat.getNumberInstance(Locale.US);
}

From source file:org.brocalc.calculator.BaseSingleBrokerageSpec.java

public BrokerageResult calculateBrokerageForTrade(String currency, String usdNotional, String tradeDate,
        String settlementDate) throws ParseException {
    NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
    BigDecimal usdAmount = new BigDecimal(format.parse(usdNotional).doubleValue());
    TradeInfo trade = mock(TradeInfo.class);
    when(trade.getCurrency()).thenReturn(Currency.getInstance(currency));
    when(trade.getUsdAmount()).thenReturn(usdAmount);
    if (tradeDate != null) {
        when(trade.getTradeDate()).thenReturn(new LocalDate(tradeDate));
    }//w  w w . ja  v  a  2 s.  c om
    if (settlementDate != null) {
        when(trade.getSettlementDate()).thenReturn(new LocalDate(settlementDate));
    }
    BrokerageAmount brokerage = brokerageSchedule.calculateBrokerage(trade);
    return BrokerageResult.fromBrokerageAmount(brokerage);
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a short primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)vv//from   w w  w. ja  va 2  s .  com
 *@return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}

From source file:me.philnate.textmanager.utils.PDFCreator.java

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {// w ww.  j av a 2 s .  co m
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:wzw.text.Formatter.java

/**
 * ?/*w ww  . ja v a2s  . c o m*/
 * @param locale 
 * @param valueToFormat ??
 * @param formatString ??
 * @return ??
 * @throws JspException
 */
public static String formatObject(Locale locale, Object valueToFormat, String formatString)
        throws JspException {
    if (valueToFormat == null || valueToFormat.toString().trim().equals("")) {
        return "";
    }

    Format format = null;
    Object value = null;
    if (value instanceof String) { //??String
        value = Double.valueOf((String) valueToFormat);
    } else {
        value = valueToFormat;
    }

    boolean formatStrFromResources = true;
    //Locale locale=Locale.getDefault();

    try {
        //     if (value instanceof java.lang.String) {
        //     return (String) value;
        //     } else {

        // Prepare format object for numeric values.
        if (value instanceof Number || value instanceof String) {

            if (formatString == null) {
                if ((value instanceof Byte) || (value instanceof Short) || (value instanceof Integer)
                        || (value instanceof Long) || (value instanceof BigInteger)) {

                    formatString = "######";

                } else if ((value instanceof Float) || (value instanceof Double)
                        || (value instanceof BigDecimal)) {

                    formatString = "######.00";
                }

                if (formatString != null) {
                    formatStrFromResources = true;
                }
            }

            if (formatString != null) {
                try {

                    format = NumberFormat.getNumberInstance(locale);
                    if (formatStrFromResources) {
                        ((DecimalFormat) format).applyLocalizedPattern(formatString);
                    } else {
                        ((DecimalFormat) format).applyPattern(formatString);
                    }

                } catch (IllegalArgumentException e) {
                    JspException ex = new JspException("write.format " + formatString);
                    //TagUtils.getInstance().saveException(pageContext, ex);
                    throw ex;
                }
            }

        } else if (value instanceof java.util.Date) {

            /*   if (formatString == null) {
                     
             if (value instanceof java.sql.Timestamp) {
             formatString =
             retrieveFormatString(SQL_TIMESTAMP_FORMAT_KEY);
                     
             } else if (value instanceof java.sql.Date) {
             formatString = retrieveFormatString(SQL_DATE_FORMAT_KEY);
                     
             } else if (value instanceof java.sql.Time) {
             formatString = retrieveFormatString(SQL_TIME_FORMAT_KEY);
                     
             } else if (value instanceof java.util.Date) {
             formatString = retrieveFormatString(DATE_FORMAT_KEY);
             }
                     
             }
                     
             if (formatString != null) {
             format = new SimpleDateFormat(formatString, locale);
             }*/
        }

        if (format != null) {
            return format.format(value);
        } else {
            return value.toString();
        }

    } catch (JspException e) {

        log.info("The format value is:[" + value.toString() + "]");
        log.debug("debug", e);
        /// e.pri ntStackTrace();
        throw e;
    }

}