Example usage for java.text DecimalFormatSymbols setDecimalSeparator

List of usage examples for java.text DecimalFormatSymbols setDecimalSeparator

Introduction

In this page you can find the example usage for java.text DecimalFormatSymbols setDecimalSeparator.

Prototype

public void setDecimalSeparator(char decimalSeparator) 

Source Link

Document

Sets the character used for decimal sign.

Usage

From source file:org.techytax.helper.AmountHelper.java

public static String format(int amount) {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    otherSymbols.setDecimalSeparator(',');
    otherSymbols.setGroupingSeparator('.');
    DecimalFormat df = new DecimalFormat("###,###,###,##0", otherSymbols);
    return df.format(amount);
}

From source file:org.techytax.helper.AmountHelper.java

public static String format(BigInteger amount) {
    if (amount == null) {
        return null;
    }/* ww w  .  j  a  v a2 s  . com*/
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    otherSymbols.setDecimalSeparator(',');
    otherSymbols.setGroupingSeparator('.');
    DecimalFormat df = new DecimalFormat("###,###,###,##0", otherSymbols);
    return df.format(amount);
}

From source file:org.techytax.helper.AmountHelper.java

public static BigInteger parse(String amount) throws ParseException {
    if (StringUtils.isEmpty(amount)) {
        return null;
    }/*from w ww.  ja v  a 2  s  . c  o  m*/
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    otherSymbols.setDecimalSeparator(',');
    otherSymbols.setGroupingSeparator('.');
    DecimalFormat df = new DecimalFormat("###,###,###,##0", otherSymbols);
    return BigInteger.valueOf(df.parse(amount).intValue());
}

From source file:org.openspaces.grid.gsm.autoscaling.AutoScalingSlaUtils.java

private static DecimalFormat initDecimalFormat() {
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator('.');
    decimalFormatSymbols.setGroupingSeparator(',');
    return new DecimalFormat("#,##0.##", decimalFormatSymbols);
}

From source file:com.insightaction.util.DataLoader.java

private static BigDecimal getBigDecimal(String value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    String pattern = "#,##0.0#";
    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
    decimalFormat.setParseBigDecimal(true);

    BigDecimal bigDecimal = null;
    try {/*  www .  j  av a2 s. c om*/
        bigDecimal = (BigDecimal) decimalFormat.parse(value);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return bigDecimal;
}

From source file:dataGen.DataGen.java

/**
 * Creates normal or uniform distributed Test-Data, without correlation.
 * The resulting Data is stored in the resources Folder.
 * @param dimensions/* w w w .  ja  v  a  2s .co  m*/
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static void genData(int dimensions, int rowCount) throws IOException {
    logger.info("Generating uniform random Data with " + rowCount + " Tuples in " + dimensions + " dimensions");
    Writer fw = new FileWriter("src/main/resources/random-" + rowCount + "-" + dimensions + ".dat");
    Random gen = new Random();

    for (int i = 1; i <= rowCount; i++) {
        // Each Row should start with the Row count
        String row = i + " ";
        // Files should be created OS/Language independent
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
        dfs.setDecimalSeparator('.');
        NumberFormat nf = new DecimalFormat("0.000000000", dfs);

        for (int j = 0; j < dimensions; j++) {
            Float n = gen.nextFloat();
            row = row + nf.format(n) + " ";
        }
        fw.write(row);
        fw.append(System.getProperty("line.separator"));
    }
    fw.close();
    logger.info(rowCount + " entries generated");
}

From source file:dataGen.DataGen.java

/**
 * Creates anti-correlated Test-Data with the specified Seed
 * The resulting Data is stored in the resources Folder.
 * @param dimensions/* w ww.j ava  2  s .  c  o  m*/
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @param gaussianData
 *       Should we create gaussian distributed Data?
 *       if false: uniform distributed Data will get created.
 * @param std
 *       standard deviation value
 * @param center
 *       center of the distribution
 * @param saveData
 *       should the Data get Saved?
 * @param seed
 *       the seed for the Random Generations
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static CustomRealMatrix genAntiCorrData(int dimensions, int rowCount, boolean gaussianData, float std,
        float center, boolean saveData, long seed) throws IOException {
    File file = null;
    // Generate the Export Files
    if (gaussianData) {
        logger.info("Generating gaussian anti-correlated Data with " + rowCount + " Tuples in " + dimensions
                + " dimensions");
        if (saveData)
            file = new File("src/main/resources/anticorr-gaussian-" + rowCount + "-" + dimensions + ".dat");
    } else {
        logger.info("Generating uniform anti-correlated Data with " + rowCount + " Tuples in " + dimensions
                + "dimensions");
        if (saveData)
            file = new File("src/main/resources/anticorr-normal-" + rowCount + "-" + dimensions + ".dat");
    }

    Random gen = new Random(seed);
    //PearsonsCorrelation corr = new PearsonsCorrelation();
    //RealMatrix corrMatrix = null;

    // Files should be created OS/Language independent
    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
    dfs.setDecimalSeparator('.');
    NumberFormat nf = new DecimalFormat("0.000000000", dfs);

    // Create a good Start-Matrix: a (dimension x dimension) matrix which fulfills the Anti-Correlation Condition
    CustomRealMatrix values = new CustomRealMatrix(rowCount, dimensions);
    int validTupleCount = 0;

    // Create the remaining Tuples
    while (validTupleCount < rowCount) {
        boolean minimalEntryFound = false;
        double entry = 0d;
        for (int j = 0; j < dimensions; j++) {
            if (gaussianData)
                entry = std * gen.nextGaussian() + center;
            else
                entry = std * gen.nextDouble() + center;

            if (!minimalEntryFound && entry < center)
                minimalEntryFound = true;
            else if (minimalEntryFound) {
                while (entry < center) {
                    if (gaussianData)
                        entry = std * gen.nextGaussian() + center;
                    else
                        entry = std * gen.nextDouble() + center;
                }
            }
            values.setEntry(validTupleCount, j, entry);
        }
        validTupleCount = validTupleCount + 1;
    }
    logger.info(values.getRowDimension() + " entries generated");
    if (saveData) {
        Writer fw = new FileWriter(file);
        saveData(values, fw, nf);
    }

    return values;
}

From source file:ch.entwine.weblounge.common.content.ResourceUtils.java

/**
 * Returns the file size formatted in <tt>bytes</tt>, <tt>kilobytes</tt>,
 * <tt>megabytes</tt>, <tt>gigabytes</tt> and <tt>terabytes</tt>, where 1 kB
 * is equal to 1'000 bytes.//from   w  w w  . j a v  a 2 s .co m
 * <p>
 * If no {@link NumberFormat} was provided,
 * <code>new DecimalFormat("0.#)</code> is used.
 * 
 * @param sizeInBytes
 *          the file size in bytes
 * @param format
 *          the number format
 * @return the file size formatted using appropriate units
 * @throws IllegalArgumentException
 *           if the file size is negative
 */
public static String formatFileSize(long sizeInBytes, NumberFormat format) throws IllegalArgumentException {
    if (sizeInBytes < 0)
        throw new IllegalArgumentException("File size cannot be negative");
    int unitSelector = 0;
    double size = sizeInBytes;

    // Calculate the size to display
    while (size >= 1000 && unitSelector < SIZE_UNITS.length) {
        size /= 1000.0d;
        unitSelector++;
    }

    // Create a number formatter, if none was provided
    if (format == null) {
        DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
        formatSymbols.setDecimalSeparator('.');
        format = new DecimalFormat("0.#", formatSymbols);
    }

    return format.format(size) + SIZE_UNITS[unitSelector];
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from  w  ww  . j a va 2  s  .  co m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.panet.imeta.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);// w w  w.  j  a  v a2 s .  co m
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new KettleValueException(message);
    }
}