Example usage for java.text DecimalFormat format

List of usage examples for java.text DecimalFormat format

Introduction

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

Prototype

public final String format(double number) 

Source Link

Document

Specialization of format.

Usage

From source file:isl.FIMS.utils.Utils.java

/**
 * Time method/*from  w ww  .j  ava2 s  . c  o m*/
 *
 * @return Current time as <CODE>String</CODE> in hh:mm:ss format
 */
public static String getTime() {
    Calendar cal = new GregorianCalendar(Locale.getDefault());

    // Get the components of the time
    //    int hour12 = cal.get(Calendar.HOUR);            // 0..11
    // Create the DecimalFormat object only one time.
    DecimalFormat myformat = new DecimalFormat("00");

    int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
    int min = cal.get(Calendar.MINUTE); // 0..59
    int sec = cal.get(Calendar.SECOND); // 0..59
    return myformat.format(hour24) + myformat.format(min) + myformat.format(sec);
    //        return new String(myformat.format(hour24)+":"+myformat.format(min)+":"+myformat.format(sec));
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static String summarizeDetailedOccupancyStats(Map<Id<Vehicle>, double[]> vehicleDistances, String del,
        int maxcap) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);//www .ja  va  2  s .c o m
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    double[] sum = new double[maxcap + 1];

    for (double[] dist : vehicleDistances.values()) {
        double emptyD = dist[0] - dist[2];
        sum[0] += emptyD;
        for (int i = 3; i < maxcap + 3; i++) {
            sum[i - 2] += dist[i];
        }
    }
    String result = "";
    for (int i = 0; i <= maxcap; i++) {
        result = result + ";" + format.format(sum[i]);
    }

    return result;
}

From source file:delfos.dataset.util.DatasetPrinter.java

private static String actuallyDoTheTable(final List<Item> itemsAllUsersRated, final List<User> users,
        DatasetLoader<? extends Rating> datasetLoader) {
    List<String> columnNames = new ArrayList<>();
    columnNames.add("user\\items");
    columnNames.addAll(//from ww w . j a va 2s .c o  m
            itemsAllUsersRated.stream().map(item -> "Item_" + item.getId()).collect(Collectors.toList()));

    Object[][] data = new Object[users.size()][itemsAllUsersRated.size() + 1];

    DecimalFormat format = new DecimalFormat("0.0000");

    IntStream.range(0, users.size()).forEach(indexUser -> {
        User user = users.get(indexUser);

        data[indexUser][0] = user.toString();

        Map<Integer, ? extends Rating> userRatingsRated = datasetLoader.getRatingsDataset()
                .getUserRatingsRated(user.getId());

        IntStream.range(0, itemsAllUsersRated.size()).forEach(indexItem -> {
            Item item = itemsAllUsersRated.get(indexItem);
            if (userRatingsRated.containsKey(item.getId())) {
                data[indexUser][indexItem + 1] = format
                        .format(userRatingsRated.get(item.getId()).getRatingValue().doubleValue());
            } else {
                data[indexUser][indexItem + 1] = "";
            }
        });
    });

    TextTable textTable = new TextTable(columnNames.toArray(new String[0]), data);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream recordingStream = new PrintStream(baos);
    textTable.printTable(recordingStream, 0);

    return baos.toString();
}

From source file:Admin_Thesaurus.ImportData.java

private static String getDate() {

    Calendar cal = new GregorianCalendar(Locale.getDefault());
    DecimalFormat myformat = new DecimalFormat("00");

    // Get the components of the date
    // int era = cal.get(Calendar.ERA);               // 0=BC, 1=AD
    int year = cal.get(Calendar.YEAR); // 2002
    int month = cal.get(Calendar.MONTH) + 1; // 0=Jan, 1=Feb, ...
    int day = cal.get(Calendar.DAY_OF_MONTH); // 1...

    //   int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday, 2=Monday
    return new String(myformat.format(day) + "-" + myformat.format(month) + "-" + year);
}

From source file:net.sf.webissues.core.WebIssuesTaskDataHandler.java

public static Set<TaskAttribute> updateTaskData(Set<TaskAttribute> changedAttributes, WebIssuesClient client,
        TaskRepository repository, TaskData data, IssueDetails issue, IProgressMonitor monitor)
        throws HttpException, ProtocolException, IOException {
    doDateAttribute(TaskAttribute.DATE_CREATION, data, changedAttributes, issue.getIssue().getCreatedDate());
    doDateAttribute(TaskAttribute.DATE_MODIFICATION, data, changedAttributes,
            issue.getIssue().getModifiedDate());

    IEnvironment environment = WebIssuesCorePlugin.getDefault().getConnector().getClientManager()
            .getClient(repository, monitor).getEnvironment();
    Folder folder = issue.getIssue().getFolder();
    IssueType type = folder.getType();/* ww w  . ja v  a 2s.  co  m*/

    // Set the project and folder attributes
    TaskAttribute projectAttribute = data.getRoot().getAttribute(WebIssuesAttribute.PROJECT.getTaskKey());
    TaskAttribute folderAttribute = data.getRoot().getAttribute(WebIssuesAttribute.FOLDER.getTaskKey());
    projectAttribute.setValue(String.valueOf(folder.getProject().getId()));
    rebuildFolders(environment, projectAttribute, data, folderAttribute,
            issue.getIssue().getFolder().getType());
    folderAttribute.setValue(String.valueOf(folder.getId()));

    // Remove all webissues attributes exception project and folder
    for (Iterator<TaskAttribute> attributeIterator = data.getRoot().getAttributes().values()
            .iterator(); attributeIterator.hasNext();) {
        TaskAttribute attr = attributeIterator.next();
        if (attr.getId().startsWith(WEBISSUES_ATTRIBUTE_KEY_PREFIX)) {
            attributeIterator.remove();
        }
    }

    // We might already have a priority attribute
    TaskAttribute priorityAttribute = data.getRoot().getAttribute(TaskAttribute.PRIORITY);

    for (Attribute attr : type.values()) {
        if (!attr.isBuiltIn() && (priorityAttribute == null || !attr.getName().equals("Priority"))) {
            String defaultValue = attr.getDefaultValue();
            String attributeId = WEBISSUES_ATTRIBUTE_KEY_PREFIX + attr.getId();

            // Set as default if nothing set
            String value = issue.getIssue().get(attr);
            if (Util.isNullOrBlank(value)) {
                value = defaultValue;
            }

            // Set up the task attribute
            TaskAttribute taskAttr = data.getRoot().createAttribute(attributeId);
            TaskAttributeMetaData metaData = taskAttr.getMetaData();
            metaData.setKind(TaskAttribute.KIND_DEFAULT);
            switch (attr.getAttributeType()) {
            case DATETIME:
                if (attr.isDateOnly()) {
                    metaData.setType(TaskAttribute.TYPE_DATE);
                } else {
                    metaData.setType(TaskAttribute.TYPE_DATETIME);
                }
                break;
            case TEXT:
                metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
                break;
            case NUMERIC:
                metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
                break;
            case USER:
                metaData.setType(TaskAttribute.TYPE_PERSON);
                metaData.setKind(TaskAttribute.KIND_PEOPLE);
                metaData.putValue("membersOnly", String.valueOf(attr.isMembersOnly()));
                if ("[Me]".equals(value)) {
                    value = type.getTypes().getEnvironment().getOwnerUser().getName();
                }
                break;
            case ENUM:
                metaData.setType(TaskAttribute.TYPE_SINGLE_SELECT);
                taskAttr.clearOptions();
                if (!attr.isRequired()) {
                    taskAttr.putOption("", "");
                }
                for (String option : attr.getOptions()) {
                    taskAttr.putOption(option, option);
                }
                break;
            }

            // Format the value if it is numeric
            if (attr.getType().equals(Attribute.AttributeType.NUMERIC) && attr.getDecimalPlaces() > 0) {
                DecimalFormat fmt = new DecimalFormat();
                fmt.setMinimumFractionDigits(attr.getDecimalPlaces());
                fmt.setMaximumFractionDigits(attr.getDecimalPlaces());
                taskAttr.setValue(fmt.format(Util.isNullOrBlank(value) ? 0d : Double.parseDouble(value)));
            } else if (attr.getType().equals(Attribute.AttributeType.DATETIME)) {
                DateFormat fmt = new SimpleDateFormat(
                        attr.isDateOnly() ? Client.DATEONLY_FORMAT : Client.DATETIME_FORMAT);
                try {
                    taskAttr.setValue(value == null ? "" : String.valueOf(fmt.parse(value).getTime()));
                } catch (ParseException e) {
                    taskAttr.setValue("");
                }
            } else {
                taskAttr.setValue(Util.nonNull(value));
            }

            metaData.setLabel(attr.getName());
        }
    }

    // Comments
    Collection<Comment> comments = issue.getComments();
    if (comments != null) {
        int count = 1;
        for (Comment comment : comments) {
            String plainText = comment.getText();
            if (Util.isNullOrBlank(plainText)) {
                continue;
            }
            TaskCommentMapper mapper = new TaskCommentMapper();
            User owner = comment.getCreatedUser();
            if (owner != null) {
                mapper.setAuthor(repository.createPerson(owner.getName()));
            }
            mapper.setCreationDate(comment.getCreatedDate().getTime());
            mapper.setText(plainText);
            mapper.setNumber(count);
            TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + count);
            mapper.applyTo(attribute);
            count++;
        }
    }

    Collection<Attachment> attachments = issue.getAttachments();
    int count = 1;
    for (Attachment attachment : attachments) {
        TaskAttachmentMapper mapper = new TaskAttachmentMapper();
        mapper.setAuthor(repository.createPerson(attachment.getCreatedUser().getName()));
        mapper.setDescription(attachment.getDescription());
        mapper.setCreationDate(attachment.getCreatedDate().getTime());
        mapper.setAttachmentId(String.valueOf(attachment.getId()));
        mapper.setFileName(attachment.getName());
        mapper.setUrl(Util.concatenateUri(repository.getRepositoryUrl(), "attachments",
                String.valueOf(attachment.getId())));
        mapper.setLength(Long.valueOf(attachment.getSize()));
        TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_ATTACHMENT + count);
        mapper.applyTo(attribute);
        count++;
    }

    count = 1;
    for (Change change : issue.getChanges()) {
        WebIssuesChangeMapper mapper = new WebIssuesChangeMapper();
        mapper.setChangeId(String.valueOf(count));
        mapper.setUser(repository.createPerson(change.getModifiedUser().getName()));
        mapper.setAttributeName(change.getAttribute() == null ? "Name" : change.getAttribute().getName());
        mapper.setType(change.getType());
        mapper.setOldValue(change.getOldValue());
        mapper.setNewValue(change.getNewValue());
        mapper.setDate(change.getModifiedDate());
        TaskAttribute attribute = data.getRoot()
                .createAttribute(WebIssuesChangeMapper.PREFIX_CHANGE + String.valueOf(count));
        mapper.applyTo(attribute);
        count++;
    }

    return changedAttributes;
}

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 ww w  .  j  a v  a2 s.  c  o 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.cloudbees.jenkins.support.impl.AboutJenkins.java

private static String humanReadableSize(long size) {
    String measure = "B";
    if (size < 1024) {
        return size + " " + measure;
    }//from   w w w  .ja  v a  2  s .c om
    double number = size;
    if (number >= 1024) {
        number = number / 1024;
        measure = "KB";
        if (number >= 1024) {
            number = number / 1024;
            measure = "MB";
            if (number >= 1024) {
                number = number / 1024;
                measure = "GB";
            }
        }
    }
    DecimalFormat format = new DecimalFormat("#0.00");
    return format.format(number) + " " + measure + " (" + size + ")";
}

From source file:com.skelril.skree.content.registry.item.currency.CofferItem.java

@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)//from ww  w  . j  a va  2s .c o m
public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) {
    DecimalFormat formatter = new DecimalFormat("#,###");
    tooltip.add(formatter.format(getCofferValue()) + " Coffers Each");
    if (stack.stackSize > 1) {
        tooltip.add(formatter.format(stack.stackSize * getCofferValue()) + " Coffers Total");
    }
}

From source file:com.anite.antelope.modules.tools.FormatterTool.java

public String getFormattedMoney(Double value) {

    DecimalFormat nf = new DecimalFormat("##,###,##0.00");

    return nf.format(value);
}

From source file:net.iubris.ipc_d3.openhours.CsvToOpenHours.java

private String getAmPm(double hours) {

    DecimalFormat df2 = new DecimalFormat("#.00");
    String hoursString = "" + df2.format(hours);
    hoursString = hoursString.replace(",", ":").replace(".", ":") + " ";
    if (hours < 12)
        hoursString += "am";
    else//from  www.  j  a  va 2 s .  c o  m
        hoursString += "pm";
    return hoursString;
}