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.itude.mobile.android.util.StringUtil.java

/**
 * Format {@link String} as a Volume/*from www. j a  v  a  2  s  .com*/
 *  
 * WARNING: Only use this method to present data to the screen
 * 
 * @param locale {@link Locale}
 * @param stringToFormat  {@link String} to format
 * @return a string formatted as a volume with group separators (eg, 131.224.000) assuming the receiver is an int string read from XML
 */
public static String formatVolume(Locale locale, String stringToFormat) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));

    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
    formatter.setMaximumFractionDigits(0);

    result = formatter.format(Double.parseDouble(stringToFormat));

    return result;
}

From source file:com.att.aro.core.util.Util.java

public static String percentageFormat(double inputValue) {
    DecimalFormat dFormat = new DecimalFormat("#.##");
    return dFormat.format(inputValue);
}

From source file:it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter.java

private static String customFormat(double value) {
    // Creating a new one since it isn't thread safe
    DecimalFormat myFormatter = new DecimalFormat("00.000000");
    return myFormatter.format(value).replace(",", ".");
}

From source file:Admin_Thesaurus.ImportData.java

/**
 * Time method// w  w  w.j  a  v a 2  s .  c o  m
 *
 * @return Current time as <CODE>String</CODE> in hh:mm:ss format
 */
private 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 new String(myformat.format(hour24) + myformat.format(min));
    //        return new String(myformat.format(hour24)+":"+myformat.format(min)+":"+myformat.format(sec));
}

From source file:com.piaoyou.util.FileUtil.java

public static String getHumanSize(long size) {

    int sizeToStringLength = String.valueOf(size).length();
    String humanSize = "";
    DecimalFormat formatter = new DecimalFormat("##0.##");
    if (sizeToStringLength > 9) {
        humanSize += formatter.format((double) size / (1024 * 1024 * 1024)) + " GB";
    } else if (sizeToStringLength > 6) {
        humanSize += formatter.format((double) size / (1024 * 1024)) + " MB";
    } else if (sizeToStringLength > 3) {
        humanSize += formatter.format((double) size / 1024) + " KB";
    } else {//from   w  w w. j av a 2  s.  c  o m
        humanSize += String.valueOf(size) + " Bytes";
    }
    return humanSize;
}

From source file:models.Service.java

/**
 * ???//from   w ww .ja v  a2s .c o m
 */
public static ObjectNodeResult saveOrUpdateByJson(User currentUser, JsonNode json) {
    JPA.em().clear();
    ObjectNodeResult result = new ObjectNodeResult();
    //      String[] notUseStrs = { "helome", "" };

    Service service = new Service();
    Service dbService = null; // ??Service
    // id
    if (json.has("id")) {
        Long id = json.findPath("id").asLong();
        if (id != null) {
            dbService = Service.queryServiceById(id);
            if (dbService != null) {
                if (dbService.getOwner() != null && dbService.getOwner().getId() - currentUser.getId() != 0) {
                    return result.error("??", "-301");
                }
                service = dbService;
            }
        }
    }
    // title
    if (json.has("title")) {
        String title = json.findPath("title").asText();
        if (StringUtils.isBlank(title)) {
            return result.error("?", "800001");
        }
        //         for (String item : notUseStrs) {
        //            if (StringUtils.contains(title, item)) {
        //               return result.error("??'" + item +"'", "800002");
        //            }
        //         }
        if (StringUtils.isNotBlank(title)) {
            title = common.SensitiveWordsFilter.doFilter(title.trim());
            title = common.ReplaceWordsFilter.doFilter(title);
        }
        service.setTitle(title);
    }
    // info
    if (json.hasNonNull("info")) {
        String info = json.findPath("info").asText();
        if (info.length() > 500) {
            return result.error("?500", "800003");
        }
        info = common.SensitiveWordsFilter.doFilter(info.trim());
        info = common.ReplaceWordsFilter.doFilter(info);
        service.setInfo(info);
    }
    // price
    if (json.has("price")) {
        DecimalFormat df = new DecimalFormat("###.00");
        Double price = null;
        String priceStr = json.findPath("price").asText();
        if (StringUtils.isNotBlank(priceStr)) {
            try {
                price = Double.parseDouble(df.format(json.findPath("price").asDouble()));
            } catch (Exception e) {
                if (Logger.isErrorEnabled()) {
                    Logger.error("?price" + price, e);
                }
            }
        }
        service.setPrice(price);
    }
    // industry
    if (json.has("industry")) {
        Long industryId = json.findPath("industry").asLong();
        SkillTag sk = SkillTag.getTagById(industryId);
        service.setIndustry(sk);
        if (sk != null) {
            service.setIndustryId(sk.getId());
        }
    }

    // tags
    if (json.has("tags") && json.get("tags").isArray()) {
        String tags = json.findPath("tags").toString();
        if (StringUtils.isNotBlank(tags)) {
            tags = common.SensitiveWordsFilter.doFilter(tags);
            tags = common.ReplaceWordsFilter.doFilter(tags);
        }
        service.setTags(tags);
    }

    // caseAttachs
    if (json.has("attachs")) {
        Iterator<JsonNode> attachs = json.findPath("attachs").elements();
        List<Long> attachIdList = new ArrayList<Long>();
        while (attachs.hasNext()) {
            Long attachId = attachs.next().findValue("attachId").asLong();
            attachIdList.add(attachId);
        }
        if (CollectionUtils.isNotEmpty(attachIdList)) {
            service.getCaseAttachs().clear();
            List<AttachOfService> attachList = new AttachOfService()
                    .queryAttachListByIdsAndCreateUserId(attachIdList, currentUser.getId());
            if (Logger.isInfoEnabled()) {
                Logger.info("serviceid" + service.getId());
            }
            // seq
            if (CollectionUtils.isNotEmpty(attachList)) {
                for (int i = 0; i < attachList.size(); ++i) {
                    attachList.get(i).seq = (long) i;
                    if (Logger.isInfoEnabled()) {
                        Logger.info("attachid" + attachList.get(i).id);
                    }
                }
                service.coverUrl = attachList.get(0).path;
            }

            Set<AttachOfService> attachSet = new HashSet<AttachOfService>(attachList);
            service.setCaseAttachs(attachSet);
        }
    }

    if (service.getId() == null || dbService == null) {
        // ?
        service.setOwner(currentUser);
        service.setOwnerId(currentUser.id);
        // ??
        service.setCreateDate(new Date());
    }

    service.saveOrUpdate();

    result.put("serviceId", service.getId());
    return result;
}

From source file:com.epam.ta.reportportal.core.widget.content.MostFailedTestCasesFilterStrategy.java

/**
 * Returned data from database converter in UI style charts
 * /*from  w  w w.j a  va  2 s . c  om*/
 * @param dbData
 * @return
 */
private static Map<String, List<ChartObject>> databaseDataConverter(Map<String, ComplexValue> dbData,
        int launches, Launch last) {
    DecimalFormat formatter = new DecimalFormat("###.##");
    Map<String, List<ChartObject>> result = new LinkedHashMap<>();
    if (dbData.keySet().isEmpty())
        return result;

    for (Entry<String, ComplexValue> pair : dbData.entrySet()) {
        ChartObject object = new ChartObject();
        Map<String, String> values = new HashMap<>();
        values.put(ALL_RUNS, String.valueOf(pair.getValue().getTotal()));
        values.put(FAILED, String.valueOf(pair.getValue().getCount()));
        double value = (double) pair.getValue().getCount() / pair.getValue().getTotal() * 100;
        values.put(AFFECTED_BY, String.valueOf(formatter.format(value)));
        values.put(LAST_FAIL_CAPTION, String.valueOf(pair.getValue().getStartTime()));
        object.setValues(values);
        result.put(pair.getKey(), Lists.newArrayList(object));
    }

    // Add last launch attr as last element
    ChartObject lastLaunch = new ChartObject();
    lastLaunch.setName(last.getName());
    lastLaunch.setNumber(last.getNumber().toString());
    lastLaunch.setId(last.getId());
    result.put(LAST_FOUND_LAUNCH, Lists.newArrayList(lastLaunch));
    return result;
}

From source file:Main.java

public static String formatCoordinate(double coordinate, int outputType) {
    StringBuilder sb = new StringBuilder();
    char endChar = DEGREE_CHAR;

    DecimalFormat df = new DecimalFormat("###.####");
    if (outputType == Location.FORMAT_MINUTES || outputType == Location.FORMAT_SECONDS) {

        df = new DecimalFormat("##.###");

        int degrees = (int) Math.floor(coordinate);
        sb.append(degrees);//  w ww. ja va  2 s.  com
        sb.append(DEGREE_CHAR); // degrees sign
        endChar = '\''; // minutes sign
        coordinate -= degrees;
        coordinate *= 60.0;

        if (outputType == Location.FORMAT_SECONDS) {

            df = new DecimalFormat("##.##");

            int minutes = (int) Math.floor(coordinate);
            sb.append(minutes);
            sb.append('\''); // minutes sign
            endChar = '\"'; // seconds sign
            coordinate -= minutes;
            coordinate *= 60.0;
        }
    }

    sb.append(df.format(coordinate));
    sb.append(endChar);

    return sb.toString();
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static String getAsString(Number number, String pattern) {
    if (number == null) {
        return "";
    }//from   w w w .  j  a  va  2  s  . c om

    DecimalFormat decimalFormat = (DecimalFormat) NumberFormat
            .getNumberInstance(LocaleSelector.instance().getLocale());
    decimalFormat.applyPattern(pattern);
    return decimalFormat.format(number);
}

From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.HexagonalRasterGenerator.java

public static void launch(Options options, String[] args) {
    /**/* w ww.j  a va  2 s  .  c o m*/
     * Initialize input parameters
     */
    int crs = 32633;
    double west = 64031;
    double east = 679874;
    double south = 5127838;
    double north = 5451301;

    double width = 10000;
    double height = width * Math.sqrt(3) / 2;

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    File homeDirectory = null;

    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption('h')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
            return;
        }
        if (cmd.hasOption('d')) {
            homeDirectory = new File(cmd.getOptionValue('d'));
            if (!homeDirectory.exists()) {
                homeDirectory = null;
            }
        } else {
            homeDirectory = null;
            log.error("Cannot find home directory");
            System.exit(0);
        }
        if (cmd.hasOption("no")) {
            north = Double.valueOf(cmd.getOptionValue('n'));
        }
        if (cmd.hasOption("ea")) {
            east = Double.valueOf(cmd.getOptionValue('e'));
        }
        if (cmd.hasOption("so")) {
            south = Double.valueOf(cmd.getOptionValue('s'));
        }
        if (cmd.hasOption("we")) {
            west = Double.valueOf(cmd.getOptionValue('w'));
        }
        if (cmd.hasOption('c')) {
            crs = Integer.valueOf(cmd.getOptionValue('c'));
        }
        if (cmd.hasOption('w')) {
            width = Double.valueOf(cmd.getOptionValue('w'));
        }
    } catch (Exception e) {
        HelpFormatter helpFormatter = new HelpFormatter();
        if (e.getMessage() != null) {
            log.error(e.getMessage() + '\n');
        } else {
            log.error("Unknown error", e);
        }
        helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
    }

    /**
     * Build feature type
     */
    SimpleFeatureTypeBuilder featureTypePoint = new SimpleFeatureTypeBuilder();
    featureTypePoint.setName("Hexagon");
    try {
        Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
        CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
        featureTypePoint.setCRS(factory.createCoordinateReferenceSystem("EPSG:" + crs));
    } catch (NoSuchAuthorityCodeException e1) {
        e1.printStackTrace();
    } catch (FactoryException e1) {
        e1.printStackTrace();
    }
    featureTypePoint.add("geom", Polygon.class);
    featureTypePoint.setDefaultGeometry("geom");
    featureTypePoint.add("id", Long.class);
    SimpleFeatureType featureType = featureTypePoint.buildFeatureType();

    /**
     * Generate raster
     */
    DecimalFormat df = new DecimalFormat("000");
    DefaultFeatureCollection raster = new DefaultFeatureCollection("hexagon_raster", featureType);

    double rowOffset = 0.0;
    double columnOffset = 0.0;

    for (int row = 0;; row++) {
        columnOffset = (row % 2 == 0) ? 0 : width / 4 * 3;

        double startY = south + rowOffset;

        double yTop = startY + height;
        double yMiddle = startY + height / 2;
        double yBottom = startY;

        for (int column = 0;; column++) {
            double startX = west + columnOffset + (column * width * 1.5);

            String id = "1" + df.format(row) + df.format(column);

            Coordinate[] coordinatesQuadrant = new Coordinate[7];
            coordinatesQuadrant[0] = new Coordinate(startX, yMiddle);
            coordinatesQuadrant[1] = new Coordinate(startX + width / 4, yBottom);
            coordinatesQuadrant[2] = new Coordinate(startX + width / 4 * 3, yBottom);
            coordinatesQuadrant[3] = new Coordinate(startX + width, yMiddle);
            coordinatesQuadrant[4] = new Coordinate(startX + width / 4 * 3, yTop);
            coordinatesQuadrant[5] = new Coordinate(startX + width / 4, yTop);
            coordinatesQuadrant[6] = coordinatesQuadrant[0];

            /** Assemble feature */
            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
            Polygon hexagon = geometryFactory
                    .createPolygon(geometryFactory.createLinearRing(coordinatesQuadrant), null);
            hexagon.setSRID(crs);
            builder.set("geom", hexagon);
            builder.set("id", id);
            raster.add(builder.buildFeature(id));

            if (startX + width > east)
                break;
        }

        if (startY + height >= north)
            break;

        rowOffset += height / 2;
    }

    final FeatureJSON json = new FeatureJSON(new GeometryJSON(7));
    boolean geometryless = raster.getSchema().getGeometryDescriptor() == null;
    json.setEncodeFeatureCollectionBounds(!geometryless);
    json.setEncodeFeatureCollectionCRS(!geometryless);
    try {
        json.writeFeatureCollection(raster,
                new FileOutputStream(homeDirectory + "/hexagonal_raster.geojson", false));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    log.info("Raster file written!");
}