Example usage for java.text NumberFormat format

List of usage examples for java.text NumberFormat format

Introduction

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

Prototype

public final String format(long number) 

Source Link

Document

Specialization of format.

Usage

From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java

public static String toHtml(CustomFormField field, Wiki wiki, String contextPath) {
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF);
        return StringUtils.toHtml(textAreaValue);
    case CustomFormField.SELECT:
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.CHECKBOX:
        if ("true".equals(field.getValue())) {
            return "Yes";
        } else {//from  w  w  w  .j a  v a 2  s . com
            return "No";
        }
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error("toHtml calendar", e);
            }
        }
        return StringUtils.toHtml(calendarValue);
    case CustomFormField.PERCENT:
        return StringUtils.toHtml(field.getValue()) + "%";
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not integer format: " + field.getValue());
            }
        }
        return integerValue;
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return decimalValue;
    case CustomFormField.CURRENCY:
        // Use a currency for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        try {
            NumberFormat formatter = NumberFormat.getCurrencyInstance();
            if (currencyCode != null) {
                Currency currency = Currency.getInstance(currencyCode);
                formatter.setCurrency(currency);
            }
            return (StringUtils.toHtml(formatter.format(StringUtils.getDoubleNumber(field.getValue()))));
        } catch (Exception e) {
            LOG.error("toHtml currency", e);
        }
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.EMAIL:
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.PHONE:
        PhoneNumberBean phone = new PhoneNumberBean();
        phone.setNumber(field.getValue());
        PhoneNumberUtils.format(phone, Locale.getDefault());
        return StringUtils.toHtml(phone.toString());
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + value;
            }
            if (value.contains("://")) {
                return ("<a href=\"" + StringUtils.toHtml(value) + "\">" + StringUtils.toHtml(value) + "</a>");
            }
        }
        return StringUtils.toHtml(value);
    case CustomFormField.IMAGE:
        String image = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(image)) {
            Project project = ProjectUtils.loadProject(wiki.getProjectId());
            return ("<img src=\"" + contextPath + "/show/" + project.getUniqueId() + "/wiki-image/" + image
                    + "\"/>");
        }
        return StringUtils.toHtml(image);
    default:
        return StringUtils.toHtml(field.getValue());
    }
}

From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java

/**
 * Convert an input Number object into a String.
 *
 * @param value The input value to be converted
 * @return the converted String value./*from   w w w. jav  a 2s .  c o  m*/
 * @throws Throwable if an error occurs converting to a String
 */
protected String convertToString(Object value) throws Throwable {

    String result = null;
    if (useLocaleFormat && value instanceof Number) {
        NumberFormat format = getFormat();
        format.setGroupingUsed(false);
        result = format.format(value);
    } else {
        result = value.toString();
    }
    return result;

}

From source file:com.prowidesoftware.swift.model.field.Field38E.java

/**
 * Returns a localized suitable for showing to humans string of a field component.<br>
 *
 * @param component number of the component to display
 * @param locale optional locale to format date and amounts, if null, the default locale is used
 * @return formatted component value or null if component number is invalid or not present
 * @throws IllegalArgumentException if component number is invalid for the field
 * @since 7.8//from w  w w.  j a va 2  s .  c  om
 */
@Override
public String getValueDisplay(int component, Locale locale) {
    if (component < 1 || component > 2) {
        throw new IllegalArgumentException("invalid component number " + component + " for field 38E");
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    if (component == 1) {
        //number or amount
        java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance(locale);
        Number n = getComponent1AsNumber();
        if (n != null) {
            return f.format(n);
        }
    }
    if (component == 2) {
        //default format (as is)
        return getComponent(2);
    }
    return null;
}

From source file:com.bdaum.zoom.gps.naming.geonaming.internal.GeoNamesService.java

@Override
public double getElevation(double lat, double lon) throws UnknownHostException, HttpException, IOException {
    NumberFormat usformat = NumberFormat.getInstance(Locale.US);
    usformat.setMaximumFractionDigits(5);
    usformat.setGroupingUsed(false);/*from   w  ww . j av  a 2 s .  c om*/
    InputStream in = openGeonamesService(NLS.bind("http://api.geonames.org/srtm3?lat={0}&lng={1}", //$NON-NLS-1$
            usformat.format(lat), usformat.format(lon)));
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
        String readLine = reader.readLine();
        if (readLine == null)
            return Double.NaN;
        try {
            double v = Double.parseDouble(readLine);
            return (v < -32000) ? Double.NaN : v;
        } catch (NumberFormatException e) {
            return Double.NaN;
        }
    }
}

From source file:com.prowidesoftware.swift.model.field.Field38B.java

/**
 * Returns a localized suitable for showing to humans string of a field component.<br>
 *
 * @param component number of the component to display
 * @param locale optional locale to format date and amounts, if null, the default locale is used
 * @return formatted component value or null if component number is invalid or not present
 * @throws IllegalArgumentException if component number is invalid for the field
 * @since 7.8//www.  j  av  a 2s . c  om
 */
@Override
public String getValueDisplay(int component, Locale locale) {
    if (component < 1 || component > 3) {
        throw new IllegalArgumentException("invalid component number " + component + " for field 38B");
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    if (component == 1) {
        //default format (as is)
        return getComponent(1);
    }
    if (component == 2) {
        //default format (as is)
        return getComponent(2);
    }
    if (component == 3) {
        //number or amount
        java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance(locale);
        Number n = getComponent3AsNumber();
        if (n != null) {
            return f.format(n);
        }
    }
    return null;
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Get a humanly readable representation of the file size.
 * If the file is a directory, the size is the aggregate of the files
 * in the directory except that subdirectories are ignored.
 * The number is given with 2 decimals./*from  w ww. j a  va  2  s .c  o  m*/
 * @param aFile a File object
 * @return a humanly readable representation of the file size (rounded)
 */
public static String getHumanReadableFileSize(File aFile) {
    ArgumentNotValid.checkNotNull(aFile, "File aFile");
    final long bytesPerOneKilobyte = 1000L;
    final long bytesPerOneMegabyte = 1000000L;
    final long bytesPerOneGigabyte = 1000000000L;
    double filesize = 0L;
    if (aFile.isDirectory()) {
        for (File f : aFile.listFiles()) {
            if (f.isFile()) {
                filesize = filesize + f.length();
            }
        }

    } else {
        filesize = aFile.length(); // normal file.
    }

    NumberFormat decFormat = new DecimalFormat("##.##");
    if (filesize < bytesPerOneKilobyte) {
        // represent size in bytes without the ".0"
        return (long) filesize + " bytes";
    } else if (filesize >= bytesPerOneKilobyte && filesize < bytesPerOneMegabyte) {
        // represent size in Kbytes
        return decFormat.format(filesize / bytesPerOneKilobyte) + " Kbytes";
    } else if (filesize >= bytesPerOneMegabyte && filesize < bytesPerOneGigabyte) {
        // represent size in Mbytes
        return decFormat.format(filesize / bytesPerOneMegabyte) + " Mbytes";
    } else {
        // represent in Gbytes
        return decFormat.format(filesize / bytesPerOneGigabyte) + " Gbytes";
    }
}

From source file:com.prowidesoftware.swift.model.field.Field136.java

/**
 * Returns a localized suitable for showing to humans string of a field component.<br>
 *
 * @param component number of the component to display
 * @param locale optional locale to format date and amounts, if null, the default locale is used
 * @return formatted component value or null if component number is invalid or not present
 * @throws IllegalArgumentException if component number is invalid for the field
 * @since 7.8/* w ww  .  ja v a 2  s  . com*/
 */
@Override
public String getValueDisplay(int component, Locale locale) {
    if (component < 1 || component > 2) {
        throw new IllegalArgumentException("invalid component number " + component + " for field 136");
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    if (component == 1) {
        //default format (as is)
        return getComponent(1);
    }
    if (component == 2) {
        //number or amount
        java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance(locale);
        Number n = getComponent2AsNumber();
        if (n != null) {
            return f.format(n);
        }
    }
    return null;
}

From source file:org.yccheok.jstock.gui.portfolio.DividendSummaryBarChartJDialog.java

private JFreeChart createBarChart(CategoryDataset dataset) {
    final int size = ((DefaultCategoryDataset) dataset).getColumnCount();
    double total = 0.0;
    for (int i = 0; i < size; i++) {
        total += ((DefaultCategoryDataset) dataset).getValue(0, i).doubleValue();
    }/*w w w .j  av  a 2s. co m*/

    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final String currencySymbol = jStockOptions.getCurrencySymbol(jStockOptions.getCountry());
    // Use apostrophes to escape currencySymbol. If currencySymbol contains
    // apostrophes, we may need to escape those by doubling them.
    final NumberFormat currencyFormat = new DecimalFormat("'" + currencySymbol.replace("'", "''") + "'#,##0");

    final String title = MessageFormat.format(
            org.yccheok.jstock.internationalization.GUIBundle
                    .getString("DividendSummaryBarChartJDialog_DividendByYear_template"),
            this.jComboBox1.getSelectedItem(), currencyFormat.format(total));
    final String domain_label = org.yccheok.jstock.internationalization.GUIBundle
            .getString("DividendSummaryBarChartJDialog_Year");
    final String range_label = org.yccheok.jstock.internationalization.GUIBundle
            .getString("DividendSummaryBarChartJDialog_Dividend");
    // create the chart...
    final JFreeChart freeChart = ChartFactory.createBarChart(title, // chart title
            domain_label, // domain axis label
            range_label, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );
    org.yccheok.jstock.charting.Utils.applyChartTheme(freeChart);
    NumberAxis rangeAxis1 = (NumberAxis) ((CategoryPlot) freeChart.getPlot()).getRangeAxis();
    rangeAxis1.setNumberFormatOverride(currencyFormat);
    return freeChart;
}

From source file:org.sentilo.samples.controller.SamplesController.java

@RequestMapping(value = { "/", "/home" })
public String runSamples(final Model model) {

    // All this data must be created in the Catalog Application before start this
    // sample execution. At least the application identity token id and the provider id must be
    // declared in system twice
    String restClientIdentityKey = samplesProperties.getProperty("rest.client.identityKey");
    String providerId = samplesProperties.getProperty("rest.client.provider");

    // For this example we have created a generic component with a status sensor that accepts text
    // type observations, only for test purpose
    String componentId = samplesProperties.getProperty("rest.client.component");
    String sensorId = samplesProperties.getProperty("rest.client.sensor");

    logger.info("Starting samples execution...");

    String observationsValue = null;
    String errorMessage = null;/*from www. j a  va  2 s .c  om*/

    try {
        // Get some system data from runtime
        Runtime runtime = Runtime.getRuntime();
        NumberFormat format = NumberFormat.getInstance();
        StringBuilder sb = new StringBuilder();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
        sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
        sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
        sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024)
                + "<br/>");

        // In this case, we're getting CPU status in text mode
        observationsValue = sb.toString();

        logger.info("Observations values: " + observationsValue);

        // Create the sample sensor, only if it doesn't exists in the catalog
        createSensorIfNotExists(restClientIdentityKey, providerId, componentId, sensorId);

        // Publish observations to the sample sensor
        sendObservations(restClientIdentityKey, providerId, componentId, sensorId, observationsValue);
    } catch (Exception e) {
        logger.error("Error publishing sensor observations: " + e.getMessage(), e);
        errorMessage = e.getMessage();
    }

    logger.info("Samples execution ended!");

    model.addAttribute("restClientIdentityKey", restClientIdentityKey);
    model.addAttribute("providerId", providerId);
    model.addAttribute("componentId", componentId);
    model.addAttribute("sensorId", sensorId);
    model.addAttribute("observations", observationsValue);

    ObjectMapper mapper = new ObjectMapper();

    try {
        if (errorMessage != null && errorMessage.length() > 0) {
            Object json = mapper.readValue(errorMessage, Object.class);
            model.addAttribute("errorMsg", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
        } else {
            model.addAttribute("successMsg", "Observations sended successfully");
        }
    } catch (Exception e) {
        logger.error("Error parsing JSON: {}", e.getMessage(), e);
        errorMessage += (errorMessage.length() > 0) ? "<br/>" : "" + e.getMessage();
        model.addAttribute("errorMsg", errorMessage);
    }

    return VIEW_SAMPLES_RESPONSE;
}

From source file:com.prowidesoftware.swift.model.field.Field132.java

/**
 * Returns a localized suitable for showing to humans string of a field component.<br>
 *
 * @param component number of the component to display
 * @param locale optional locale to format date and amounts, if null, the default locale is used
 * @return formatted component value or null if component number is invalid or not present
 * @throws IllegalArgumentException if component number is invalid for the field
 * @since 7.8//w  ww.  ja va  2  s .  c o  m
 */
@Override
public String getValueDisplay(int component, Locale locale) {
    if (component < 1 || component > 2) {
        throw new IllegalArgumentException("invalid component number " + component + " for field 132");
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    if (component == 1) {
        //default format (as is)
        return getComponent(1);
    }
    if (component == 2) {
        //number or amount
        java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance(locale);
        Number n = getComponent2AsNumber();
        if (n != null) {
            return f.format(n);
        }
    }
    return null;
}