Example usage for java.text NumberFormat setGroupingUsed

List of usage examples for java.text NumberFormat setGroupingUsed

Introduction

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

Prototype

public void setGroupingUsed(boolean newValue) 

Source Link

Document

Set whether or not grouping will be used in this format.

Usage

From source file:org.j2free.jsp.el.StandardExtensions.java

/**
 *
 * @param n/*from  ww w  .j a  va2  s .  co m*/
 * @return
 */
public static String commify(int n) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(true);
    return nf.format(n);
}

From source file:org.apache.nifi.schemaregistry.processors.CSVUtils.java

/**
 * Writes {@link GenericRecord} as CSV (delimited) record to the
 * {@link OutputStream} using provided delimiter.
 *//* ww w . j a  v a  2s . c o m*/
public static void write(GenericRecord record, char delimiter, OutputStream out) {
    List<Field> fields = record.getSchema().getFields();

    String delimiterToUse = "";
    try {
        for (Field field : fields) {
            out.write(delimiterToUse.getBytes(StandardCharsets.UTF_8));
            Object fieldValue = record.get(field.name());
            if (null == fieldValue) {
                out.write(new byte[0]);
            } else {
                if (Type.BYTES == field.schema().getType()) {
                    // need to create it from the ByteBuffer it is serialized as.
                    // need to ensure the type is one of the logical ones we support and if so convert it.
                    if (!"decimal".contentEquals(field.getProp("logicalType"))) {
                        throw new IllegalArgumentException(
                                "The field '" + field.name() + "' has a logical type of '"
                                        + field.getProp("logicalType") + "' that is currently not supported.");
                    }

                    JsonNode rawPrecision = field.getJsonProp("precision");
                    if (null == rawPrecision) {
                        throw new IllegalArgumentException(
                                "The field '" + field.name() + "' is missing the required precision property");
                    }
                    int precision = rawPrecision.asInt();
                    JsonNode rawScale = field.getJsonProp("scale");
                    int scale = null == rawScale ? 0 : rawScale.asInt();

                    // write out the decimal with the precision and scale.
                    NumberFormat numberFormat = DecimalFormat.getInstance();
                    numberFormat.setGroupingUsed(false);
                    normalizeNumberFormat(numberFormat, scale, precision);
                    final String rawValue = new String(((ByteBuffer) fieldValue).array());
                    out.write(numberFormat.format(new BigDecimal(rawValue)).getBytes(StandardCharsets.UTF_8));
                } else {
                    out.write(fieldValue.toString().getBytes(StandardCharsets.UTF_8));
                }
            }
            if (delimiterToUse.length() == 0) {
                delimiterToUse = String.valueOf(delimiter);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException("Failed to parse AVRO Record", e);
    }
}

From source file:org.openestate.io.core.NumberUtils.java

/**
 * Write a number into a string value.//from  w  w w .j  av  a  2  s .com
 *
 * @param value
 * the number to write
 *
 * @param integerDigits
 * maximal number of integer digits
 *
 * @param fractionDigits
 * maximal number of fraction digits
 *
 * @param locale
 * locale for decimal separator (using {@link Locale#ENGLISH} if null)
 *
 * @return
 * the formatted number
 */
public static String printNumber(Number value, int integerDigits, int fractionDigits, Locale locale) {
    if (value == null)
        return null;
    NumberFormat format = NumberFormat.getNumberInstance((locale != null) ? locale : Locale.ENGLISH);
    format.setMaximumIntegerDigits(integerDigits);
    format.setMaximumFractionDigits(fractionDigits);
    format.setMinimumFractionDigits(0);
    format.setGroupingUsed(false);
    return format.format(value);
}

From source file:com.streamsets.datacollector.util.SystemProcessImpl.java

/**
 * @return a unique number which shorts in descending order
 */// ww w  .java  2 s . c om
private static String nextId() {
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setMinimumIntegerDigits(10);
    numberFormat.setGroupingUsed(false);
    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd_HH.mm.ss");
    return Utils.format("{}-{}", dateFormat.format(new Date()),
            numberFormat.format(fileCounter.incrementAndGet()));
}

From source file:edu.kit.dama.rest.util.RestClientUtils.java

/**
 * Build REST URL from a given pattern and its values. There is no check for
 * correct number of arguments. While generating URL all arguments will
 * encoded to be in a correct format. E.g.: 'stupid example' will be
 * transformed to 'stupid%20example'./*  w w  w .j  a v a2s . com*/
 *
 * @param pattern URL with any number of place holders for arguments
 * @param arguments array of arguments for the place holders
 * @return encoded URL
 */
public static String encodeUrl(String pattern, Object... arguments) {
    List<Object> urlArg = new ArrayList<>();
    for (Object arg : arguments) {
        if (arg == null) {
            throw new IllegalArgumentException("Null-values not supported for any element of 'arguments'.");
        }
        if (arg instanceof Number) {
            // everyting should work fine!
            NumberFormat instance = NumberFormat.getInstance(Locale.US);
            instance.setGroupingUsed(false);
            instance.setMaximumFractionDigits(9);
            String number = instance.format(arg);
            urlArg.add(number);
        } else if (arg instanceof String) {
            urlArg.add(encode((String) arg));
        } else {
            LOGGER.warn("Uncovered argument type {}", arg);
        }
    }
    String returnValue = MessageFormat.format(pattern, urlArg.toArray());

    LOGGER.debug("Final URL: {}", returnValue);

    return returnValue;
}

From source file:com.nextgis.mobile.forms.CompassFragment.java

public static String formatNumber(Object value, int max, int min) {

    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumFractionDigits(max);// w w w  .  j a v a  2s  .c  o  m
    f.setMinimumFractionDigits(min);
    f.setGroupingUsed(false);

    try {
        return f.format(value);
    } catch (IllegalArgumentException e) {
        return "err";
    }

}

From source file:com.nextgis.maplibui.fragment.CompassFragment.java

public static String formatNumber(Object value, int max, int min) {
    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumFractionDigits(max);//from   ww  w  .j av a  2  s. c  o m
    f.setMinimumFractionDigits(min);
    f.setGroupingUsed(false);

    try {
        return f.format(value);
    } catch (IllegalArgumentException e) {
        return e.getLocalizedMessage();
    }
}

From source file:org.kalypso.ogc.sensor.timeseries.TimeseriesUtils.java

/**
 * Returns the adequate NumberFormat for the given format-string. It currently only supports formats of the form %X.Yf
 * where actually only the Y is used to build a NumberFormat with Y minimum/maximum-fraction-digits.
 * <p>/*  w  w  w  .  j  a v  a2  s. com*/
 * The plan is, once we'll be using JDK 5.0, we'll try to replace this with the built-in functionality provided with
 * formated printing.
 * <p>
 * TODO once on JDK 5.0 use formated printing if possible. Note that some refactoring might need to be done since we
 * currently work with NumberFormats.
 */
public static synchronized NumberFormat getNumberFormat(final String format) {
    final NumberFormat nf = FORMAT_MAP.get(format);
    if (nf != null)
        return nf;

    if ("%d".equals(format)) //$NON-NLS-1$
    {
        final NumberFormat wf = NumberFormat.getIntegerInstance();
        wf.setGroupingUsed(false);
        FORMAT_MAP.put(format, wf);
        return wf;
    }

    // parse the format spec and only take the min-fraction-digit part
    final String regex = "%([0-9]*)\\.?([0-9]*)f"; //$NON-NLS-1$
    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher(format);
    if (matcher.matches()) {
        final String minfd = matcher.group(2);

        final NumberFormat wf = NumberFormat.getInstance();
        final int intValue = Integer.valueOf(minfd).intValue();
        wf.setMinimumFractionDigits(intValue);
        wf.setMaximumFractionDigits(intValue);
        FORMAT_MAP.put(format, wf);

        return wf;
    }

    return getDefaultFormat();
}

From source file:org.orbisgis.corejdbc.ReadTable.java

/**
 * Return a concatened and human readable format of provided result set
 * @param rs result set to read/*  w  w  w  .jav a  2  s . c  om*/
 * @param maxFieldLength Maximum field length to print
 * @param maxPrintedRows Maximum printed rows
 * @param addColumns Add column header
 * @param alignColumns Align columns by using padding
 * @param resultSetFilter Accept or refuse rows by implementing this interface
 * @return human readable format of provided result set
 * @throws SQLException
 */
public static String resultSetToString(ResultSet rs, int maxFieldLength, int maxPrintedRows, boolean addColumns,
        boolean alignColumns, ResultSetFilter resultSetFilter) throws SQLException {
    // Print headers
    ResultSetMetaData metaData = rs.getMetaData();
    int columnCount = metaData.getColumnCount();
    StringBuilder lines = new StringBuilder();
    StringBuilder formatStringBuilder = new StringBuilder();
    String[] header = new String[columnCount];
    for (int idColumn = 1; idColumn <= columnCount; idColumn++) {
        header[idColumn - 1] = metaData.getColumnLabel(idColumn) + "(" + metaData.getColumnTypeName(idColumn)
                + ")";
        if (alignColumns) {
            formatStringBuilder.append("%-");
            formatStringBuilder.append(maxFieldLength);
            formatStringBuilder.append("s ");
        } else {
            formatStringBuilder.append("%s ");
        }
    }
    if (addColumns) {
        lines.append(String.format(formatStringBuilder.toString(), header));
        lines.append("\n");
    }
    int shownLines = 0;
    NumberFormat decimalFormat = NumberFormat.getInstance(Locale.getDefault());
    decimalFormat.setGroupingUsed(false);
    decimalFormat.setMaximumFractionDigits(16);
    while (rs.next() && shownLines < maxPrintedRows) {
        if (resultSetFilter.printRow(rs)) {
            String[] row = new String[columnCount];
            for (int idColumn = 1; idColumn <= columnCount; idColumn++) {
                Object valObj = rs.getObject(idColumn);
                String value;
                if (valObj instanceof Number) {
                    value = decimalFormat.format(valObj);
                } else {
                    value = rs.getString(idColumn);
                }
                if (value != null) {
                    if (columnCount > 1 && value.length() > maxFieldLength) {
                        value = value.substring(0, maxFieldLength - 2) + "..";
                    }
                } else {
                    value = "NULL";
                }
                row[idColumn - 1] = value;
            }
            shownLines++;
            lines.append(String.format(formatStringBuilder.toString(), row));
            lines.append("\n");
        }
    }
    if (lines.length() != 0) {
        return lines.toString();
    } else {
        return I18N.tr("No attributes to show");
    }
}

From source file:us.fatehi.pointlocation6709.format.PointLocationFormatter.java

private static NumberFormat getNumberFormat(final int integerDigits) {
    final NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setMinimumIntegerDigits(integerDigits);
    numberFormat.setMinimumFractionDigits(5);
    numberFormat.setMaximumFractionDigits(5);
    numberFormat.setGroupingUsed(false);
    return numberFormat;
}