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:com.nkapps.billing.services.NumberServiceImpl.java

@Override
public String convertToText(Double number) {
    if (number == 0) {
        return "00";
    }//from  w  w  w .ja v a2 s.  c  om

    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    String snumber = df.format(number.longValue());

    int billions = Integer.parseInt(snumber.substring(0, 3));
    int millions = Integer.parseInt(snumber.substring(3, 6));
    int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
    int thousands = Integer.parseInt(snumber.substring(9, 12));

    String tradBillions;
    switch (billions) {
    case 0:
        tradBillions = "";
        break;
    default:
        tradBillions = convertLessThanOneThousand(billions) + "  ";
    }
    String result = tradBillions;

    String tradMillions;
    switch (millions) {
    case 0:
        tradMillions = "";
        break;
    default:
        tradMillions = convertLessThanOneThousand(millions) + "  ";
    }
    result = result + tradMillions;

    String tradHundredThousands;
    switch (hundredThousands) {
    case 0:
        tradHundredThousands = "";
        break;
    case 1:
        tradHundredThousands = "?? ";
        break;
    default:
        tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " ??";
    }
    result = result + tradHundredThousands;

    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result = result + tradThousand;
    Double tiyin = number - number.intValue();
    // remove extra spaces!
    return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ") + " ? "
            + (tiyin.equals(0) ? "00" : Double.valueOf(tiyin * 100).intValue()) + " ";
}

From source file:com.nextgis.maplibui.formcontrol.Coordinates.java

public String getFormattedValue() {
    DecimalFormat format = new DecimalFormat("#.######", new DecimalFormatSymbols(Locale.US));
    return format.format(mValue);
}

From source file:com.safetys.framework.jmesa.core.filter.NumberFilterMatcher.java

public boolean evaluate(Object itemValue, String filterValue) {
    if (itemValue == null) {
        return false;
    }//from   ww  w .  j av a  2  s.  c om

    Locale locale = null;

    WebContext webContext = getWebContext();
    if (webContext != null) {
        locale = webContext.getLocale();
    }

    NumberFormat nf;
    if (locale != null) {
        nf = NumberFormat.getInstance(locale);
    } else {
        nf = NumberFormat.getInstance();
    }

    DecimalFormat df = (DecimalFormat) nf;
    String pattern = getPattern();
    df.applyPattern(pattern);
    itemValue = df.format(itemValue);

    String item = String.valueOf(itemValue);
    String filter = String.valueOf(filterValue);
    if (StringUtils.contains(item, filter)) {
        return true;
    }

    return false;
}

From source file:com.carfinance.module.statisticsmanage.service.StatisticsManageService.java

public Map<String, Object> getVehicleList(String vehicle_model, String license_plate, String begin_date,
        String end_date, int start, int size) {
    Map<String, Date> map_tmp = getStringToDate(begin_date, end_date);
    Date begin = map_tmp.get("begin");
    Date end = map_tmp.get("end");

    long total = this.statisticsManageDao.getVehicleCount(vehicle_model, license_plate, begin, end);
    List<VehicleIncom> vehicleList = this.statisticsManageDao.getVehicleList(vehicle_model, license_plate,
            begin, end, start, size);//from   w w w  .ja v a  2s .co  m
    for (VehicleIncom vehicleIncom : vehicleList) {
        double total_price = vehicleIncom.getOver_price() + vehicleIncom.getActually_price();
        DecimalFormat df = new DecimalFormat("#.00");
        total_price = Double.valueOf(df.format(total_price));

        vehicleIncom.setTotal_price(total_price);
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("total", total);
    map.put("vehicle_list", vehicleList);
    return map;
}

From source file:com.fatwire.dta.sscrawler.reporting.reporters.NestingReporter.java

@Override
public void endCollecting() {
    report.startReport();//from   w w  w.  j  ava 2s .  c om
    report.addHeader("threshold", Integer.toString(threshold));
    report.addHeader("uri", "nesting");

    for (final QueryString qs : tracker.getKeys()) {
        if (qs instanceof Link) {
            final int level = tracker.getNestingLevel(qs);
            total.addValue(level);
            if (level >= threshold) {
                count.incrementAndGet();

                report.addRow(qs.toString(), Integer.toString(level));
            } else if (level == 0) {
                report.addRow(qs.toString(), Integer.toString(level));
            }
        }
    }
    final DecimalFormat df = new DecimalFormat("###0.00");
    report.addRow("Average Nesting level", df.format(total.getMean()));
    report.addRow("Maximum Nesting level", Long.toString(Math.round(total.getMax())));
    report.addRow("Minimum Nesting level", Long.toString(Math.round(total.getMin())));
    super.endCollecting();
}

From source file:com.carfinance.module.statisticsmanage.service.StatisticsManageService.java

public Map<String, Object> getReoprtList(String vehicle_model, String license_plate, String report_type,
        int start, int size) {
    //        String begin_date = null;
    //        String end_date = null;

    Map<String, Date> beginEndMap = this.commonService.getBeginEndDate(report_type);
    Date begin_date = beginEndMap.get("begin");
    Date end_date = beginEndMap.get("end");

    long total = this.statisticsManageDao.getReoprtCount(vehicle_model, license_plate, begin_date, end_date);
    List<VehicleIncom> vehicleList = this.statisticsManageDao.getReoprtList(vehicle_model, license_plate,
            begin_date, end_date, start, size);
    for (VehicleIncom vehicleIncom : vehicleList) {
        double total_price = vehicleIncom.getOver_price() + vehicleIncom.getActually_price();
        DecimalFormat df = new DecimalFormat("#.00");
        total_price = Double.valueOf(df.format(total_price));

        vehicleIncom.setTotal_price(total_price);
    }/*from  w ww.  j  a  va2s  .  c om*/

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("total", total);
    map.put("vehicle_list", vehicleList);
    return map;
}

From source file:com.alibaba.dubbo.monitor.simple.SimpleMonitorService.java

private static void createChart(String key, String service, String method, String date, String[] types,
        Map<String, long[]> data, double[] summary, String path) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
    DecimalFormat numberFormat = new DecimalFormat("###,##0.##");
    TimeSeriesCollection xydataset = new TimeSeriesCollection();
    for (int i = 0; i < types.length; i++) {
        String type = types[i];/*w w w. j  a va 2 s.com*/
        TimeSeries timeseries = new TimeSeries(type);
        for (Map.Entry<String, long[]> entry : data.entrySet()) {
            try {
                timeseries.add(new Minute(dateFormat.parse(date + entry.getKey())), entry.getValue()[i]);
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            }
        }
        xydataset.addSeries(timeseries);
    }
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(
            "max: " + numberFormat.format(summary[0])
                    + (summary[1] >= 0 ? " min: " + numberFormat.format(summary[1]) : "") + " avg: "
                    + numberFormat.format(summary[2])
                    + (summary[3] >= 0 ? " sum: " + numberFormat.format(summary[3]) : ""),
            toDisplayService(service) + "  " + method + "  " + toDisplayDate(date), key, xydataset, true, true,
            false);
    jfreechart.setBackgroundPaint(Color.WHITE);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setBackgroundPaint(Color.WHITE);
    xyplot.setDomainGridlinePaint(Color.GRAY);
    xyplot.setRangeGridlinePaint(Color.GRAY);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
    dateaxis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
    BufferedImage image = jfreechart.createBufferedImage(600, 300);
    try {
        if (logger.isInfoEnabled()) {
            logger.info("write chart: " + path);
        }
        File methodChartFile = new File(path);
        File methodChartDir = methodChartFile.getParentFile();
        if (methodChartDir != null && !methodChartDir.exists()) {
            methodChartDir.mkdirs();
        }
        FileOutputStream output = new FileOutputStream(methodChartFile);
        try {
            ImageIO.write(image, "png", output);
            output.flush();
        } finally {
            output.close();
        }
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }
}

From source file:com.yahoo.platform.yuitest.coverage.results.DirectoryCoverageReport.java

/**
 * Returns the percentage of lines called.
 * @return The percentage of lines called.
 * @throws org.json.JSONException/*from ww w.  j  a  v a  2 s. c om*/
 */
public double getCalledLinePercentage() throws JSONException {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double
            .valueOf(twoDForm.format(((double) getCalledLineCount() / (double) getCoveredLineCount()) * 100));
}

From source file:com.yahoo.platform.yuitest.coverage.results.DirectoryCoverageReport.java

/**
 * Returns the percentage of functions called.
 * @return The percentage of functions called.
 * @throws org.json.JSONException//from   www .  ja  va 2  s.  c om
 */
public double getCalledFunctionPercentage() throws JSONException {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(
            twoDForm.format(((double) getCalledFunctionCount() / (double) getCoveredFunctionCount()) * 100));
}

From source file:net.mozq.picto.core.ProcessCore.java

private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData,
        Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException {

    ProcessDataStatus status;/* www . ja va  2  s  .  c  om*/

    Path destParentPath = processData.getDestPath().getParent();
    if (destParentPath != null) {
        Files.createDirectories(destParentPath);
    }

    if (processCondition.isCheckDigest()
            || (processCondition.isChangeExifDate() && processData.getBaseDate() != null)
            || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) {
        Path destTempPath = null;
        try {
            destTempPath = Files.createTempFile(processData.getDestPath().getParent(),
                    processData.getDestPath().getFileName().toString(), null);

            if (processCondition.isCheckDigest()) {
                String algorithm = FILE_DIGEST_ALGORITHM;

                MessageDigest srcMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) {
                    Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE);
                }
                byte[] srcDigest = srcMD.digest();

                MessageDigest destMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) {
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                    }
                }
                byte[] destDigest = destMD.digest();

                if (!isSame(srcDigest, destDigest)) {
                    throw new PictoFileDigestMismatchException(
                            Messages.getString("message.error.digest.mismatch"));
                }
            } else if (processCondition.isRemveExifTagsAll()) {
                ExifRewriter exifRewriter = new ExifRewriter();
                try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                    exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os);
                } catch (ImageReadException | ImageWriteException e) {
                    throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                }
            } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) {
                ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath());
                TiffOutputSet outputSet = getOutputSet(imageMetadata);
                if (outputSet == null) {
                    Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE);
                } else {
                    if (processCondition.isChangeExifDate()) {
                        SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN);
                        exifDateFormat.setTimeZone(processCondition.getTimeZone());
                        String exifBaseDate = exifDateFormat.format(processData.getBaseDate());

                        DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN);
                        String exifBaseSubsec = exifSubsecFormat
                                .format((int) (processData.getBaseDate().getTime() / 10) % 100);

                        try {
                            TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
                            TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                            if (rootDirectory != null) {
                                rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME);
                                rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate);
                            }
                            if (exifDirectory != null) {
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
                                        exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
                                        exifBaseSubsec);
                            }
                        } catch (ImageWriteException e) {
                            throw new PictoFileChangeException(Messages.getString("message.error.edit.file"),
                                    e);
                        }
                    }

                    if (processCondition.isRemveExifTagsGps()) {
                        outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO);
                    }

                    ExifRewriter exifRewriter = new ExifRewriter();
                    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                        exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os,
                                outputSet);
                    } catch (ImageReadException | ImageWriteException e) {
                        throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                    }
                }
            }

            Path destPath;
            if (processCondition.getOperationType() == OperationType.Overwrite) {
                destPath = processData.getSrcPath();
            } else {
                destPath = processData.getDestPath();
            }
            try {
                Files.move(destTempPath, destPath, OPTIONS_MOVE);
                if (processCondition.getOperationType() == OperationType.Move) {
                    Files.deleteIfExists(processData.getSrcPath());
                }
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    // Overwrite
                    Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE);
                    if (processCondition.getOperationType() == OperationType.Move) {
                        Files.deleteIfExists(processData.getSrcPath());
                    }
                    status = ProcessDataStatus.Success;
                }
            }
        } finally {
            if (destTempPath != null) {
                Files.deleteIfExists(destTempPath);
            }
        }
    } else {
        switch (processCondition.getOperationType()) {
        case Copy:
            try {
                Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Move:
            try {
                Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Overwrite:
            // NOP
            status = ProcessDataStatus.Success;
            break;
        default:
            throw new IllegalStateException(processCondition.getOperationType().toString());
        }
    }

    if (status == ProcessDataStatus.Success) {
        FileTime creationFileTime = processData.getSrcFileAttributes().creationTime();
        FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime();
        FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime();
        if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate()
                || processCondition.isChangeFileAccessDate()) {
            if (processData.getBaseDate() != null) {
                FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime());
                if (processCondition.isChangeFileCreationDate()) {
                    creationFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileModifiedDate()) {
                    modifiedFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileAccessDate()) {
                    accessFileTime = baseFileTime;
                }
            }
        }
        BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(),
                BasicFileAttributeView.class);
        attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime);
    }

    return status;
}