Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

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

Prototype

public DecimalFormatSymbols(Locale locale) 

Source Link

Document

Create a DecimalFormatSymbols object for the given locale.

Usage

From source file:org.jvnet.hudson.plugins.repositoryconnector.aether.ConsoleTransferListener.java

public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);//from w  w w .  ja v a  2s.  c  o  m

    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";

        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }

        out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
                + throughput + ")");
    }
}

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

public static BigInteger parse(String amount) throws ParseException {
    if (StringUtils.isEmpty(amount)) {
        return null;
    }/*from   ww  w . ja v a2  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:com.runwaysdk.business.generation.maven.TransferListener.java

@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);/*from  w  w w  .j av a 2  s.c o  m*/

    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";

        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }

        log.info(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
                + throughput + ")");
    }
}

From source file:com.itude.mobile.android.util.StringUtil.java

public static String formatNumberWithOriginalNumberOfDecimals(String stringToFormat, Locale locale) {

    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }/*from  w  ww . java2s. co m*/

    String result = null;

    DecimalFormat formatter = new DecimalFormat("#################.####################",
            new DecimalFormatSymbols(locale));

    try {
        result = formatter.format(Double.parseDouble(stringToFormat));
    } catch (Exception e) {
        MBLog.w(TAG, "Could not format string " + stringToFormat
                + " as number with original number of decimals (StringUtilities)", e);

        return null;
    }

    return result;
}

From source file:fr.cs.examples.propagation.VisibilityCircle.java

private void run(final File input, final File output, final String separator)
        throws IOException, IllegalArgumentException, OrekitException {

    // read input parameters
    KeyValueFileParser<ParameterKey> parser = new KeyValueFileParser<ParameterKey>(ParameterKey.class);
    parser.parseInput(new FileInputStream(input));

    double minElevation = parser.getAngle(ParameterKey.MIN_ELEVATION);
    double radius = Constants.WGS84_EARTH_EQUATORIAL_RADIUS
            + parser.getDouble(ParameterKey.SPACECRAFT_ALTITUDE);
    int points = parser.getInt(ParameterKey.POINTS_NUMBER);

    // station properties
    double latitude = parser.getAngle(ParameterKey.STATION_LATITUDE);
    double longitude = parser.getAngle(ParameterKey.STATION_LONGITUDE);
    double altitude = parser.getDouble(ParameterKey.STATION_ALTITUDE);
    String name = parser.getString(ParameterKey.STATION_NAME);

    // compute visibility circle
    List<GeodeticPoint> circle = computeCircle(latitude, longitude, altitude, name, minElevation, radius,
            points);/*from w  w w. ja  v a2  s .  com*/

    // create a 2 columns csv file representing the visibility circle
    // in the user home directory, with latitude in column 1 and longitude in column 2
    DecimalFormat format = new DecimalFormat("#00.00000", new DecimalFormatSymbols(Locale.US));
    PrintStream csvFile = new PrintStream(output);
    for (GeodeticPoint p : circle) {
        csvFile.println(format.format(FastMath.toDegrees(p.getLatitude())) + ","
                + format.format(FastMath.toDegrees(p.getLongitude())));
    }
    csvFile.close();

}

From source file:com.mendhak.gpslogger.common.OpenGTSClient.java

/**
 * Encode a location as GPRMC string data.
 * <p/>//from   w w  w.  ja  v a 2s  . co  m
 * For details check org.opengts.util.Nmea0183#_parse_GPRMC(String)
 * (OpenGTS source)
 *
 * @param loc location
 * @return GPRMC data
 */
public static String GPRMCEncode(SerializableLocation loc) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
    DecimalFormat f = new DecimalFormat("0.000000", dfs);

    String gprmc = String.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,,", "$GPRMC",
            NMEAGPRMCTime(new Date(loc.getTime())), "A", NMEAGPRMCCoord(Math.abs(loc.getLatitude())),
            (loc.getLatitude() >= 0) ? "N" : "S", NMEAGPRMCCoord(Math.abs(loc.getLongitude())),
            (loc.getLongitude() >= 0) ? "E" : "W", f.format(MetersPerSecondToKnots(loc.getSpeed())),
            f.format(loc.getBearing()), NMEAGPRMCDate(new Date(loc.getTime())));

    gprmc += "*" + NMEACheckSum(gprmc);

    return gprmc;
}

From source file:org.yes.cart.web.page.component.customer.order.CustomerOrderPanel.java

/**
 * {@inheritDoc}/*from w w  w  .  j av  a  2s.  c om*/
 */
@Override
protected void onBeforeRender() {
    final Customer customer = (Customer) getDefaultModel().getObject();
    final SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT, getLocale());

    final DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.US);
    final DecimalFormat decimalFormat = new DecimalFormat(Constants.MONEY_FORMAT, formatSymbols);

    final Date date = determineDate(getPage().getPageParameters());
    final List<CustomerOrder> orders = getValidCustomerOrderInChronologicalOrder(customer, date);

    if (orders.isEmpty()) {

        addOrReplace(new Label(ORDER_INFORMATION, getLocalizer().getString("noOrders", this)));

    } else {

        addOrReplace(new Fragment(ORDER_INFORMATION, ORDER_INFORMATION_FRAGMENT, this)
                .add(new ListView<CustomerOrder>(ORDER_LIST, orders) {
                    protected void populateItem(final ListItem<CustomerOrder> customerOrderListItem) {

                        final CustomerOrder order = customerOrderListItem.getModelObject();
                        final Pair<String, Boolean> symbol = currencySymbolService
                                .getCurrencySymbol(order.getCurrency());
                        final BigDecimal amount = order.getOrderTotal();

                        customerOrderListItem
                                .add(determineOrderPageLink(order, CustomerOrderPanel.ORDER_VIEW_LINK))
                                .add(new Label(ORDER_NUM, order.getOrdernum()))
                                .add(new Label(ORDER_DATE, dateFormat.format(order.getOrderTimestamp())))
                                .add(new Label(ORDER_STATE,
                                        getLocalizer().getString(order.getOrderStatus(), this)))
                                .add(new Label(ORDER_ITEMS, getItemsList(order)).setEscapeModelStrings(false))
                                .add(new Label(ORDER_AMOUNT,
                                        symbol.getSecond()
                                                ? decimalFormat.format(amount) + " " + symbol.getFirst()
                                                : symbol.getFirst() + " " + decimalFormat.format(amount)));

                    }
                }));

    }

    super.onBeforeRender();
}

From source file:org.mitre.math.linear.RandomMatrixExample.java

/**
 * // w  w  w. j  a v  a  2 s .c o  m
 * @param m
 * @param width      Column width.
 * @param digits     Number of digits after the decimal.
 * @return
 */
public String matrix2String(RealMatrix m, int width, int digits) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    format.setMinimumFractionDigits(digits);
    format.setGroupingUsed(false);

    StringBuilder output = new StringBuilder();
    output.append('\n'); // start on new line.
    for (int i = 0; i < m.getRowDimension(); i++) {
        for (int j = 0; j < m.getColumnDimension(); j++) {
            String s = format.format(m.getEntry(i, j)); // format the number
            int padding = Math.max(1, width - s.length()); // At _least_ 1 space
            for (int k = 0; k < padding; k++) {
                output.append(' ');
            }
            output.append(s);
        }
        output.append('\n');
    }
    output.append('\n'); // end with blank line.
    return output.toString();
}

From source file:net.sourceforge.subsonic.util.StringUtil.java

/**
 * Converts a byte-count to a formatted string suitable for display to the user.
 * For instance:/*w w w  .  j a va2s  . c o m*/
 * <ul>
 * <li><code>format(918)</code> returns <em>"918 B"</em>.</li>
 * <li><code>format(98765)</code> returns <em>"96 KB"</em>.</li>
 * <li><code>format(1238476)</code> returns <em>"1.2 MB"</em>.</li>
 * </ul>
 * This method assumes that 1 KB is 1024 bytes.
 *
 * @param byteCount The number of bytes.
 * @param locale    The locale used for formatting.
 * @return The formatted string.
 */
public static synchronized String formatBytes(long byteCount, Locale locale) {

    // More than 1 GB?
    if (byteCount >= 1024 * 1024 * 1024) {
        NumberFormat gigaByteFormat = new DecimalFormat("0.00 GB", new DecimalFormatSymbols(locale));
        return gigaByteFormat.format((double) byteCount / (1024 * 1024 * 1024));
    }

    // More than 1 MB?
    if (byteCount >= 1024 * 1024) {
        NumberFormat megaByteFormat = new DecimalFormat("0.0 MB", new DecimalFormatSymbols(locale));
        return megaByteFormat.format((double) byteCount / (1024 * 1024));
    }

    // More than 1 KB?
    if (byteCount >= 1024) {
        NumberFormat kiloByteFormat = new DecimalFormat("0 KB", new DecimalFormatSymbols(locale));
        return kiloByteFormat.format((double) byteCount / 1024);
    }

    return byteCount + " B";
}

From source file:org.opencastproject.silencedetection.ffmpeg.FFmpegSilenceDetector.java

/**
 * Create nonsilent sequences detection pipeline.
 * Parse audio stream and store all positions, where the volume level fall under the threshold.
 *
 * @param properties//from www  .  ja v a2s  . co m
 * @param track source track
 */
public FFmpegSilenceDetector(Properties properties, Track track, Workspace workspace)
        throws SilenceDetectionFailedException, MediaPackageException, IOException {

    long minSilenceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.SILENCE_MIN_LENGTH, DEFAULT_SILENCE_MIN_LENGTH));
    long minVoiceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.VOICE_MIN_LENGTH, DEFAULT_VOICE_MIN_LENGTH));
    long preSilenceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.SILENCE_PRE_LENGTH, DEFAULT_SILENCE_PRE_LENGTH));
    String thresholdDB = properties.getProperty(SilenceDetectionProperties.SILENCE_THRESHOLD_DB,
            DEFAULT_THRESHOLD_DB);

    String binary = properties.getProperty(FFMPEG_BINARY_CONFIG, FFMPEG_BINARY_DEFAULT);

    trackId = track.getIdentifier();

    /* Make sure the element can be analyzed using this analysis implementation */
    if (!track.hasAudio()) {
        logger.warn("Track {} has no audio stream to run a silece detection on", trackId);
        throw new SilenceDetectionFailedException("Element has no audio stream");
    }

    /* Make sure we are not allowed to move the beginning of a segment into the last segment */
    if (preSilenceLength > minSilenceLength) {
        logger.error("Pre silence length ({}) is configured to be greater than minimun silence length ({})",
                preSilenceLength, minSilenceLength);
        throw new SilenceDetectionFailedException("preSilenceLength > minSilenceLength");
    }

    try {
        File mediaFile = workspace.get(track.getURI());
        filePath = mediaFile.getAbsolutePath();
    } catch (NotFoundException e) {
        throw new SilenceDetectionFailedException("Error finding the media file in workspace", e);
    } catch (IOException e) {
        throw new SilenceDetectionFailedException("Error reading media file in workspace", e);
    }

    if (track.getDuration() == null) {
        throw new MediaPackageException("Track " + trackId + " does not have a duration");
    }
    logger.info("Track {} loaded, duration is {} s", filePath, track.getDuration() / 1000);

    logger.info("Starting silence detection of {}", filePath);
    String mediaPath = filePath.replaceAll(" ", "\\ ");
    DecimalFormat decimalFmt = new DecimalFormat("0.000", new DecimalFormatSymbols(Locale.US));
    String minSilenceLengthInSeconds = decimalFmt.format((double) minSilenceLength / 1000.0);
    String filter = "silencedetect=noise=" + thresholdDB + ":duration=" + minSilenceLengthInSeconds;
    String[] command = new String[] { binary, "-nostats", "-i", mediaPath, "-filter:a", filter, "-f", "null",
            "-" };
    String commandline = StringUtils.join(command, " ");

    logger.info("Running {}", commandline);

    ProcessBuilder pbuilder = new ProcessBuilder(command);
    List<String> segmentsStrings = new LinkedList<String>();
    Process process = pbuilder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    try {
        LineReader lr = new LineReader(reader);
        String line = lr.readLine();
        while (null != line) {
            /* We want only lines from the silence detection filter */
            logger.debug("FFmpeg output: {}", line);
            if (line.startsWith("[silencedetect ")) {
                segmentsStrings.add(line);
            }
            line = lr.readLine();
        }
    } catch (IOException e) {
        logger.error("Error executing ffmpeg: {}", e.getMessage());
    } finally {
        reader.close();
    }

    /**
     * Example output:
     * [silencedetect @ 0x2968e40] silence_start: 466.486
     * [silencedetect @ 0x2968e40] silence_end: 469.322 | silence_duration: 2.83592
     */

    LinkedList<MediaSegment> segmentsTmp = new LinkedList<MediaSegment>();
    if (segmentsStrings.size() == 0) {
        /* No silence found -> Add one segment for the whole track */
        logger.info("No silence found. Adding one large segment.");
        segmentsTmp.add(new MediaSegment(0, track.getDuration()));
    } else {
        long lastSilenceEnd = 0;
        long lastSilenceStart = 0;
        Pattern patternStart = Pattern.compile("silence_start\\:\\ \\d+\\.\\d+");
        Pattern patternEnd = Pattern.compile("silence_end\\:\\ \\d+\\.\\d+");
        for (String seginfo : segmentsStrings) {
            /* Match silence ends */
            Matcher matcher = patternEnd.matcher(seginfo);
            String time = "";
            while (matcher.find()) {
                time = matcher.group().substring(13);
            }
            if (!"".equals(time)) {
                long silenceEnd = (long) (Double.parseDouble(time) * 1000);
                if (silenceEnd > lastSilenceEnd) {
                    logger.debug("Found silence end at {}", silenceEnd);
                    lastSilenceEnd = silenceEnd;
                }
                continue;
            }

            /* Match silence start -> End of segments */
            matcher = patternStart.matcher(seginfo);
            time = "";
            while (matcher.find()) {
                time = matcher.group().substring(15);
            }
            if (!"".equals(time)) {
                lastSilenceStart = (long) (Double.parseDouble(time) * 1000);
                logger.debug("Found silence start at {}", lastSilenceStart);
                if (lastSilenceStart - lastSilenceEnd > minVoiceLength) {
                    /* Found a valid segment */
                    long segmentStart = java.lang.Math.max(0, lastSilenceEnd - preSilenceLength);
                    logger.info("Adding segment from {} to {}", segmentStart, lastSilenceStart);
                    segmentsTmp.add(new MediaSegment(segmentStart, lastSilenceStart));
                }
            }
        }
        /* Add last segment if it is no silence and the segment is long enough */
        if (lastSilenceStart < lastSilenceEnd && track.getDuration() - lastSilenceEnd > minVoiceLength) {
            long segmentStart = java.lang.Math.max(0, lastSilenceEnd - preSilenceLength);
            logger.info("Adding final segment from {} to {}", segmentStart, track.getDuration());
            segmentsTmp.add(new MediaSegment(segmentStart, track.getDuration()));
        }
    }

    logger.info("Segmentation of track {} yielded {} segments", trackId, segmentsTmp.size());
    segments = segmentsTmp;

}