Java 类java.text.DecimalFormat 实例源码

项目:happybot    文件:Hypixel.java   
public HashMap<String, String> getAllFields(HypixelPlayer hypixelPlayer) {
    HashMap<String, String> fields = new HashMap<>();
    if (hypixelPlayer != null) {
        DecimalFormat df = new DecimalFormat("#.#");
        fields.put("Network Level", df.format(hypixelPlayer.getAbsoluteLevel()));
        fields.put("Rank", hypixelPlayer.getCurrentRank());
        fields.put("MC Version", hypixelPlayer.getMcVersionRp());
        fields.put("Bedwars Wins", String.valueOf(hypixelPlayer.getAchievements().getBedwarsWins()));
        fields.put("Bedwars Level", String.valueOf(hypixelPlayer.getAchievements().getBedwarsLevel()));
        fields.put("Karma", String.valueOf(hypixelPlayer.getKarma()));
        fields.put("Language", hypixelPlayer.getUserLanguage());
        fields.put("Vanity Tokens", String.valueOf(hypixelPlayer.getVanityTokens()));
        fields.put("Join Date", new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date(hypixelPlayer.getFirstLogin())));
        fields.put("Last Join", new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date(hypixelPlayer.getLastLogin())));
    }
    return fields;
}
项目:acmeair    文件:JtlTotals.java   
public String cntByTimeString() {
    DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN);
    List<String> millisStr = new LinkedList<String>();

    Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator();
    while(iter.hasNext()) {
        Entry<Integer,Integer> millisEntry = iter.next();
        Integer bucket = (Integer)millisEntry.getKey();
        Integer bucketCount = (Integer)millisEntry.getValue();

        int minMillis = bucket.intValue() * millisPerBucket;
        int maxMillis = (bucket.intValue() + 1) * millisPerBucket;

        millisStr.add(
          df.format(minMillis/MILLIS_PER_SECOND)+" s "+
          "- "+
          df.format(maxMillis/MILLIS_PER_SECOND)+" s "+
          "= " + bucketCount);
    }
    return millisStr.toString();
}
项目:jmt    文件:NumberOfCustomersPanel.java   
/**
 * @return the object at (rowIndex, columnIndex)
 */
@Override
protected Object getValueAtImpl(int rowIndex, int columnIndex) {
    String toReturn;
    Object thisClass = cd.getClosedClassKeys().get(columnIndex);
    double thisPop = cd.getClassPopulation(thisClass).doubleValue();
    double totalPop = cd.getTotalClosedClassPopulation();
    if (rowIndex == 0) {
        toReturn = Integer.toString((int) thisPop);
    } else {
        DecimalFormat twoDec = new DecimalFormat("0.00");
        double beta = 0;
        if (totalPop > 0) {
            beta = thisPop / totalPop;
        }
        toReturn = twoDec.format(beta);
    }
    return toReturn;
}
项目:micrometer    文件:DoubleFormat.java   
@Override
protected NumberFormat initialValue() {

    // Always create the formatter for the US locale in order to avoid this bug:
    // https://github.com/indeedeng/java-dogstatsd-client/issues/3
    final NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
    numberFormatter.setGroupingUsed(false);
    numberFormatter.setMaximumFractionDigits(6);

    // we need to specify a value for Double.NaN that is recognized by dogStatsD
    if (numberFormatter instanceof DecimalFormat) { // better safe than a runtime error
        final DecimalFormat decimalFormat = (DecimalFormat) numberFormatter;
        final DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
        symbols.setNaN("NaN");
        decimalFormat.setDecimalFormatSymbols(symbols);
    }

    return numberFormatter;
}
项目:MapAnalyst    文件:DistortionGrid.java   
/**
 * Returns a string that can be used in a dialog to inform the user that the
 * grid has not a correct size, i.e. the number of lines is too small or too
 * large.
 */
private String getErrorMessageForIncorrectNumberOfGridLines(Grid grid,
        Rectangle2D srcPointsExtension) {

    double cellSize = grid.getSuggestedCellSize(srcPointsExtension);
    String msg = "With the current mesh size, the new distortion"
            + "\ngrid would contain less than ";
    msg += MIN_NODES;
    msg += " or more than ";
    msg += MAX_NODES;
    msg += "\nvertical or horizontal lines.";
    msg += "\nPlease enter a different value in the Mesh Size field. ";
    msg += "\nA suggested value is ";
    msg += new DecimalFormat("#,##0.#########").format(cellSize);
    if (meshUnit == Unit.DEGREES) {
        msg += "\u00B0";
    } else {
        msg += " meters";
    }
    msg += ".";
    return msg;
}
项目:bean-grid    文件:AbstractStringToNumberConverterBean.java   
/**
 * Returns the format used by
 * {@link #convertToPresentation(Object, ValueContext)} and
 * {@link #convertToModel(Object, ValueContext)}.
 *
 * @param context
 *            value context to use
 * @return A NumberFormat instance
 */
protected NumberFormat getFormat(ValueContext context) {
    String pattern = null;

    Object data = context.getComponent().map(AbstractComponent.class::cast).map(component -> component.getData())
            .orElse(null);
    if (data instanceof ColumnDefinition) {
        pattern = ((ColumnDefinition) data).getFormat()
                .orElse(configurationProvider.getNumberFormatPattern().orElse(null));
    }

    Locale locale = context.getLocale().orElse(configurationProvider.getLocale());

    if (pattern == null) {
        return NumberFormat.getNumberInstance(locale);
    }

    return new DecimalFormat(pattern, new DecimalFormatSymbols(locale));
}
项目:htsjdk-s3-plugin    文件:PerformanceMonitor.java   
/**
 * A method for logging the current counters state, as well as the average downloading speed.
 */
static void printSummary() {
    long curTimeMillis = System.currentTimeMillis();
    double elapsedMinutes = (((double) curTimeMillis - startTime) / MILLISEC_IN_SEC) / SECS_IN_MINUTE;
    double averageSpeed = dataLoaded.doubleValue() /
            ((curTimeMillis - startTime) / MILLISEC_IN_SEC) / KILO / KILO;

    log.info(requestCounter.longValue()
            + " GetRequests made, "
            + dataLoaded.longValue()
            + " bytes downloaded. Average speed: "
            + new DecimalFormat("#0.00").format(averageSpeed)
            + " MB/s. Time Elapsed: "
            + new DecimalFormat("#0.00").format(elapsedMinutes) + " minutes"
    );

}
项目:openjdk-jdk10    文件:Bug6609740.java   
private static void parseOnPattern(NumberFormat nf, String pattern,
        String parseString, Number expected) {

    if (nf instanceof DecimalFormat) {
        ((DecimalFormat) nf).applyPattern(pattern);
    }

    try {
        Number output = nf.parse(parseString);
        if (expected.doubleValue() != output.doubleValue()) {
            throw new RuntimeException("[FAILED: Unable to parse the number"
                    + " based on the pattern: '" + pattern + "', Expected : '"
                    + expected + "', Found: '" + output + "']");
        }
    } catch (ParseException ex) {
        throw new RuntimeException("[FAILED: Unable to parse the pattern:"
                + " '" + pattern + "']", ex);
    }
}
项目:QN-ACTR-Release    文件:NumberOfCustomersPanel.java   
/**
 * @return the object at (rowIndex, columnIndex)
 */
@Override
protected Object getValueAtImpl(int rowIndex, int columnIndex) {
    String toReturn;
    Object thisClass = cd.getClosedClassKeys().get(columnIndex);
    double thisPop = cd.getClassPopulation(thisClass).doubleValue();
    double totalPop = cd.getTotalCloseClassPopulation();
    if (rowIndex == 0) {
        toReturn = Integer.toString((int) thisPop);
    } else {
        DecimalFormat twoDec = new DecimalFormat("0.00");
        double beta = thisPop / totalPop;
        toReturn = twoDec.format(beta);
    }
    return toReturn;
}
项目:unitimes    文件:PositionTypes.java   
@Override
@PreAuthorize("checkPermission('PositionTypes')")
public SimpleEditInterface load(SessionContext context, Session hibSession) {
    SimpleEditInterface data = new SimpleEditInterface(
            new Field(MESSAGES.fieldReference(), FieldType.text, 160, 20, Flag.UNIQUE),
            new Field(MESSAGES.fieldName(), FieldType.text, 300, 60, Flag.UNIQUE),
            new Field(MESSAGES.fieldSortOrder(), FieldType.number, 80, 10, Flag.UNIQUE)
            );
    data.setSortBy(2, 0, 1);
    DecimalFormat df = new DecimalFormat("0000");
    for (PositionType position: PositionTypeDAO.getInstance().findAll()) {
        int used =
            ((Number)hibSession.createQuery(
                    "select count(f) from Staff f where f.positionType.uniqueId = :uniqueId")
                    .setLong("uniqueId", position.getUniqueId()).uniqueResult()).intValue() +
            ((Number)hibSession.createQuery(
                    "select count(f) from DepartmentalInstructor f where f.positionType.uniqueId = :uniqueId")
                    .setLong("uniqueId", position.getUniqueId()).uniqueResult()).intValue();
        Record r = data.addRecord(position.getUniqueId(), used == 0);
        r.setField(0, position.getReference());
        r.setField(1, position.getLabel());
        r.setField(2, df.format(position.getSortOrder()));
    }
    data.setEditable(context.hasPermission(Right.PositionTypeEdit));
    return data;
}
项目:Zero    文件:Utils.java   
public static String bytes2String(long sizeInBytes) {

        NumberFormat nf = new DecimalFormat();
        nf.setMaximumFractionDigits(1);
        nf.setMinimumFractionDigits(1);

        try {
            if (sizeInBytes < SPACE_KB) {
                return nf.format(sizeInBytes) + " Byte(s)";
            } else if (sizeInBytes < SPACE_MB) {
                return nf.format(sizeInBytes / SPACE_KB) + " KB";
            } else if (sizeInBytes < SPACE_GB) {
                return nf.format(sizeInBytes / SPACE_MB) + " MB";
            } else if (sizeInBytes < SPACE_TB) {
                return nf.format(sizeInBytes / SPACE_GB) + " GB";
            } else {
                return nf.format(sizeInBytes / SPACE_TB) + " TB";
            }
        } catch (Exception e) {
            return sizeInBytes + " Byte(s)";
        }

    }
项目:karate    文件:Script.java   
private static BigDecimal convertToBigDecimal(Object o) {
    DecimalFormat df = new DecimalFormat();
    df.setParseBigDecimal(true);
    try {
        return (BigDecimal) df.parse(o.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:parabuild-ci    文件:RelativeDateFormat.java   
/**
 * Creates a new instance.
 * 
 * @param baseMillis  the time zone (<code>null</code> not permitted).
 */
public RelativeDateFormat(long baseMillis) {
    super();        
    this.baseMillis = baseMillis;
    this.showZeroDays = false;
    this.dayFormatter = NumberFormat.getInstance();
    this.daySuffix = "d";
    this.hourSuffix = "h";
    this.minuteSuffix = "m";
    this.secondFormatter = NumberFormat.getNumberInstance();
    this.secondFormatter.setMaximumFractionDigits(3);
    this.secondFormatter.setMinimumFractionDigits(3);
    this.secondSuffix = "s";

    // we don't use the calendar or numberFormat fields, but equals(Object) 
    // is failing without them being non-null
    this.calendar = new GregorianCalendar();
    this.numberFormat = new DecimalFormat("0");    
}
项目:parabuild-ci    文件:StandardCategoryItemLabelGeneratorTests.java   
/**
 * Some checks for the generalLabel() method.
 */
public void testGenerateLabel() {
    StandardCategoryItemLabelGenerator g 
        = new StandardCategoryItemLabelGenerator("{2}", 
                new DecimalFormat("0.000"));
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.addValue(1.0, "R0", "C0");
    dataset.addValue(2.0, "R0", "C1");
    dataset.addValue(3.0, "R1", "C0");
    dataset.addValue(null, "R1", "C1");
    String s = g.generateLabel(dataset, 0, 0);
    assertEquals("1.000", s);

    // try a null value
    s = g.generateLabel(dataset, 1, 1);
    assertEquals("-", s);
}
项目:sonar-analyzer-commons    文件:LineIssues.java   
@Override
public String toString() {
  if (messages.isEmpty()) {
    return "";
  }
  StringBuilder out = new StringBuilder();
  appendLineNumber(out, line);
  out.append(COMMENT_PREFIX);
  boolean oneMessageIsMissing = messages.stream().filter(Objects::isNull).count() > 0;
  if (oneMessageIsMissing && messages.size() > 1) {
    out.append(" ").append(messages.size());
  }
  messages.stream()
    .filter(Objects::nonNull)
    .sorted()
    .forEach(message -> out.append(" {{").append(message).append("}}"));
  Double effort = effortToFix();
  if (effort != null) {
    DecimalFormat effortToFixFormat = new DecimalFormat("0.##");
    out.append(" [[effortToFix=").append(effortToFixFormat.format(effort)).append("]]");
  }
  out.append("\n");
  appendLocations(out);
  return out.toString();
}
项目:ipack    文件:NTRUSigningKeyGenerationParameters.java   
public String toString()
{
    DecimalFormat format = new DecimalFormat("0.00");

    StringBuilder output = new StringBuilder("SignatureParameters(N=" + N + " q=" + q);
    if (polyType == NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE)
    {
        output.append(" polyType=SIMPLE d=" + d);
    }
    else
    {
        output.append(" polyType=PRODUCT d1=" + d1 + " d2=" + d2 + " d3=" + d3);
    }
    output.append(" B=" + B + " basisType=" + basisType + " beta=" + format.format(beta) +
        " normBound=" + format.format(normBound) + " keyNormBound=" + format.format(keyNormBound) +
        " prime=" + primeCheck + " sparse=" + sparse + " keyGenAlg=" + keyGenAlg + " hashAlg=" + hashAlg + ")");
    return output.toString();
}
项目:incubator-netbeans    文件:FormatSelector.java   
/**
 * Returns format's pattern. 
 * 
 * @return format's pattern.
 */
public String getFormat() {
    if (format != null) return format;
    String fmt = null;
    if (formatter instanceof MaskFormatter) {
        fmt = ((MaskFormatter)formatter).getMask();
    } else if (formatter instanceof InternationalFormatter) {
        Format f = ((InternationalFormatter)formatter).getFormat();
        if (f instanceof DecimalFormat) {
            fmt = ((DecimalFormat)f).toPattern();
        } else if (f instanceof SimpleDateFormat) {
            fmt = ((SimpleDateFormat)f).toPattern();
        }
    }
    return fmt;
}
项目:PaySim    文件:AggregateParamFileCreator.java   
public static double getStdv(ArrayList<Transaction> list, double average){
    DecimalFormat df = new DecimalFormat("#.##");
    double stdv = 0;
    double squaredMeanSum = 0;

    //For each number, subtract the mean and square the result
    for(int i=0; i<list.size(); i++){
        double currVal = list.get(i).getAmount() - average;
        currVal *= currVal;
        //System.out.println("Adding :\t" + currVal + "\n");
        squaredMeanSum += currVal;
    }
    //System.out.println("Squred diff  sum\n" + squaredMeanSum + "\n");
    squaredMeanSum /= (double) list.size()-1;
    //System.out.println("Dividing with:\t" + list.size() + "\n");

    return Math.sqrt(squaredMeanSum);
}
项目:Mobike    文件:Utils.java   
public static String distanceFormatter(int distance) {
    if (distance < 1000) {
        return distance + "米";
    } else if (distance % 1000 == 0) {
        return distance / 1000 + "公里";
    } else {
        DecimalFormat df = new DecimalFormat("0.0");
        int a1 = distance / 1000; // 十位

        double a2 = distance % 1000;
        double a3 = a2 / 1000; // 得到个位

        String result = df.format(a3);
        double total = Double.parseDouble(result) + a1;
        return total + "公里";
    }
}
项目:EVideoRecorder    文件:FileUtils.java   
/**
 * 转换文件大小,指定转换的类型
 *
 * @param fileS
 * @param sizeType
 * @return
 */
public static double FormetFileSize(long fileS, int sizeType) {
    DecimalFormat df = new DecimalFormat("#.00");
    double fileSizeLong = 0;
    switch (sizeType) {
        case SIZETYPE_B:
            fileSizeLong = Double.valueOf(df.format((double) fileS));
            break;
        case SIZETYPE_KB:
            fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
            break;
        case SIZETYPE_MB:
            fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
            break;
        case SIZETYPE_GB:
            fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
            break;
        default:
            break;
    }
    return fileSizeLong;
}
项目:mycat-src-1.6.1-RELEASE    文件:TestSelectPerf.java   
public static void report(CopyOnWriteArrayList<SelectJob> jobs) {
    double tps = 0;
    long maxTTL = 0;
    long minTTL = Integer.MAX_VALUE;
    long ttlCount = 0;
    long ttlSum = 0;
    DecimalFormat df = new DecimalFormat("0.00");
    for (SelectJob job : jobs) {
        double jobTps = job.getTPS();
        if (jobTps > 0) {
            tps += job.getTPS();
            if (job.getMaxTTL() > maxTTL) {
                maxTTL = job.getMaxTTL();
            }
            if (job.getMinTTL() < minTTL) {
                minTTL = job.getMinTTL();
            }
            ttlCount += job.getValidTTLCount();
            ttlSum += job.getValidTTLSum();
        }
    }
    double avgSum =(ttlCount > 0) ? (ttlSum+0.0) / ttlCount : 0;
    System.out.println("finishend:" + finshiedCount.get() + " failed:"
            + failedCount.get() + " qps:" + df.format(tps) + ",query time min:"
            + minTTL + "ms,max:" + maxTTL + "ms,avg:" + df.format(avgSum) );
}
项目:ditb    文件:OneMeasurementHdrHistogram.java   
/**
 * This is called periodically from the StatusThread. There's a single
 * StatusThread per Client process. We optionally serialize the interval to
 * log on this opportunity.
 *
 * @see ditb.ycsb.measurements.OneMeasurement#getSummary()
 */
@Override public String getSummary() {
  Histogram intervalHistogram = getIntervalHistogramAndAccumulate();
  // we use the summary interval as the histogram file interval.
  if (histogramLogWriter != null) {
    histogramLogWriter.outputIntervalHistogram(intervalHistogram);
  }

  DecimalFormat d = new DecimalFormat("#.##");
  return "[" + getName() + ": Count=" + intervalHistogram.getTotalCount() + ", Max="
      + intervalHistogram.getMaxValue() + ", Min=" + intervalHistogram.getMinValue() + ", Avg="
      + d.format(intervalHistogram.getMean()) + ", 90=" + d
      .format(intervalHistogram.getValueAtPercentile(90)) + ", 99=" + d
      .format(intervalHistogram.getValueAtPercentile(99)) + ", 99.9=" + d
      .format(intervalHistogram.getValueAtPercentile(99.9)) + ", 99.99=" + d
      .format(intervalHistogram.getValueAtPercentile(99.99)) + "]";
}
项目:letv    文件:GarbageCleanActivity.java   
private static String getFloatValue(double oldValue, int decimals) {
    if (oldValue >= 1000.0d) {
        decimals = 0;
    } else if (oldValue >= 100.0d) {
        decimals = 1;
    }
    BigDecimal b = new BigDecimal(oldValue);
    if (decimals <= 0) {
        try {
            oldValue = (double) b.setScale(0, 1).floatValue();
        } catch (ArithmeticException e) {
            Log.w("Unit.getFloatValue", e.getMessage());
        }
    } else {
        oldValue = (double) b.setScale(decimals, 1).floatValue();
    }
    String decimalStr = "";
    if (decimals <= 0) {
        decimalStr = "#";
    } else {
        for (int i = 0; i < decimals; i++) {
            decimalStr = decimalStr + "#";
        }
    }
    return new DecimalFormat("###." + decimalStr).format(oldValue);
}
项目:BEAST    文件:BEASTCommunicator.java   
/**
 * Creates a String that contains the given time in seconds in a readable format.
 * @param passedTimeSeconds the passed time in seconds as a double
 */
private String createTimeString(double passedTimeSeconds) {
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    String timeString = "";
    if (passedTimeLongerThanDay(passedTimeSeconds)) {
        timeString = createTimeStringLongerThanDay(passedTimeSeconds, decimalFormat);
    } else if (passedTimeLongerThanHour(passedTimeSeconds)) {
        timeString = createTimeStringLongerThanHour(passedTimeSeconds, decimalFormat);
    } else if (passedTimeLongerThanMinute(passedTimeSeconds)) {
        timeString = createTimeStringLongerThanMinute(passedTimeSeconds, decimalFormat);
    } else {
        String seconds = decimalFormat.format(passedTimeSeconds);
        timeString = seconds + "s";
    }
    return timeString;
}
项目:shareNote    文件:FileUtils.java   
/**
 * 自动判断因该转换的单位
 *
 * @param size 大小
 * @return 转换后的大小
 */
public static String formatSize(long size) {
    if (size == 0L) {
        return "0B";
    }
    DecimalFormat df = new DecimalFormat("#.00");
    if (size < 1024) {
        return df.format(formatSize(size, SizeType.B)) + "B";
    }
    if (size < 1024 * 1024) {
        return df.format(formatSize(size, SizeType.KB)) + "KB";
    }
    if (size < 1024 * 1024 * 1024) {
        return df.format(formatSize(size, SizeType.MB)) + "MB";
    }

    if (size >= 1024 * 1024 * 1024) {
        double formatSized = formatSize(size, SizeType.GB);
        if (formatSized >= 1024) {
            return df.format(formatSized / 1024) + "TB";
        }
        return df.format(formatSized) + "GB";
    }
    return null;
}
项目:boohee_v5.6    文件:DecodedBitStreamParser.java   
static DecoderResult decode(byte[] bytes, int mode) {
    StringBuilder result = new StringBuilder(144);
    switch (mode) {
        case 2:
        case 3:
            String postcode;
            if (mode == 2) {
                postcode = new DecimalFormat("0000000000".substring(0, getPostCode2Length
                        (bytes))).format((long) getPostCode2(bytes));
            } else {
                postcode = getPostCode3(bytes);
            }
            String country = THREE_DIGITS.format((long) getCountry(bytes));
            String service = THREE_DIGITS.format((long) getServiceClass(bytes));
            result.append(getMessage(bytes, 10, 84));
            if (!result.toString().startsWith("[)>\u001e01\u001d")) {
                result.insert(0, postcode + GS + country + GS + service + GS);
                break;
            }
            result.insert(9, postcode + GS + country + GS + service + GS);
            break;
        case 4:
            result.append(getMessage(bytes, 1, 93));
            break;
        case 5:
            result.append(getMessage(bytes, 1, 77));
            break;
    }
    return new DecoderResult(bytes, result.toString(), null, String.valueOf(mode));
}
项目:onprom    文件:LogExtractorUsageExample1.java   
private static String getRunningTimeString(String label, String tab, long time){

    DecimalFormat f = new DecimalFormat("###,###.###");

    return label + tab + 
            String.format("%20s", f.format(time)) + " msec. / ~"+ 
            String.format("%3.2f", (double)time/1000)+ " sec. / ~"+ 
            String.format("%3.2f", (double)time/60000)+" min. ";
}
项目:SOS-The-Healthcare-Companion    文件:AddReadingActivity.java   
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int seconds) {
    TextView addTime = (TextView) findViewById(R.id.dialog_add_time);
    DecimalFormat df = new DecimalFormat("00");

    presenter.setReadingHour(df.format(hourOfDay));
    presenter.setReadingMinute(df.format(minute));

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
    cal.set(Calendar.MINUTE, minute);
    FormatDateTime formatDateTime = new FormatDateTime(getApplicationContext());
    addTime.setText(formatDateTime.getTime(cal));
}
项目:EatDubbo    文件:PerformanceUtils.java   
public static List<String> getEnvironment() {
    List<String> environment = new ArrayList<String>();
    environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch", ""));
    environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
    environment.add("JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
    environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) 
                               + " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
    NetworkInterface ni = PerformanceUtils.getNetworkInterface();
    if (ni != null) {
        environment.add("Network: " + ni.getDisplayName());
    }
    return environment;
}
项目:oscm    文件:PriceConverter.java   
@Override
protected Format getFormat(String pattern, Locale locale) {
    DecimalFormat format = (DecimalFormat) super.getFormat(pattern,
            locale);
    format.setMaximumIntegerDigits(NUMBER_OF_INTEGER_PLACES);
    format.setMaximumFractionDigits(NUMBER_OF_DECIMAL_PLACES);
    // avoid lost precision due to parsing to double:
    format.setParseBigDecimal(true);
    return format;
}
项目:uavstack    文件:DiskIOCollector.java   
public void collectWin(Map<String, Map<String, String>> resultMap) {

        try {
            String output = RuntimeHelper.exec(
                    "wmic path Win32_PerfFormattedData_PerfDisk_LogicalDisk get DiskReadBytesPerSec,DiskWriteBytesPerSec,Name");

            if (StringHelper.isEmpty(output)) {
                return;
            }

            String[] strs = output.split("\n");
            for (String str : strs) {
                str = str.replaceAll("\\s{2,}", " ");
                String[] args = str.split(" ");
                if (1 == args.length) {
                    continue;
                }

                if (!(args[2].equals("_Total")) && !(args[2].equals("Name"))) {
                    double rd_persec = Long.parseLong(args[0]) / 1024.0;
                    double wr_persec = Long.parseLong(args[1]) / 1024.0;

                    DecimalFormat df = new DecimalFormat("#0.00");
                    resultMap.get(args[2]).put("disk_read", df.format(rd_persec));
                    resultMap.get(args[2]).put("disk_write", df.format(wr_persec));
                }
            }
        }
        catch (Exception e) {
            // ignore
        }
    }
项目:Endless    文件:Stats.java   
@Override
protected void execute(CommandEvent event)
{
    String title = ":information_source: Stats of **"+event.getSelfUser().getName()+"**:";
    Color color;
    String os = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getName();
    String arch = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getArch();
    String version = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getVersion();
    os = os+" "+arch+" "+version;
    int cpus = Runtime.getRuntime().availableProcessors();
    String processCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getProcessCpuLoad());
    String systemCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class).getSystemCpuLoad());
    long ramUsed = ((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()) / (1024 * 1024));

    if(event.isFromType(ChannelType.PRIVATE))
        color = Color.decode("#33ff00");
    else
        color = event.getGuild().getSelfMember().getColor();

    EmbedBuilder builder = new EmbedBuilder();
    builder.addField("<:windows:371075985996775425> OS: ", os, true);
    builder.addField(":computer: RAM usage: ", ramUsed+"MB", true);
    builder.addField(":gear: CPU usage: ", processCpuLoad+" / "+systemCpuLoad+" ("+cpus+" Cores)", true);
    builder.addField(":map: Guilds: ", ""+event.getJDA().getGuilds().size() , true);
    builder.addField(":speech_balloon: Text Channels: ", ""+event.getJDA().getTextChannels().size(), true);
    builder.addField(":speaker: Voice Channels: ", ""+event.getJDA().getVoiceChannels().size(), true);
    builder.addField(":bust_in_silhouette: Users: ", ""+event.getJDA().getUsers().size(), true);
    builder.setFooter(event.getSelfUser().getName(), event.getSelfUser().getEffectiveAvatarUrl());
    builder.setColor(color);
    event.getChannel().sendMessage(new MessageBuilder().append(title).setEmbed(builder.build()).build()).queue();
}
项目:Persephone    文件:MetricsCacheGridRow.java   
public MetricsCacheGridRow(MetricsCache metric) {
    this.name = metric.getName();
    this.size = metric.getSize();

    DecimalFormat format = new DecimalFormat("#.## %");
    this.hit = format.format(metric.getHitRatio());
    this.miss = format.format(metric.getMissRatio());
}
项目:NotifyTools    文件:DecimalLocaleConverter.java   
/**
 * Convert the specified locale-sensitive input object into an output
 * object of the specified type.
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return The converted value
 *
 * @throws org.apache.commons.beanutils.ConversionException if conversion
 * cannot be performed successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
@Override
protected Object parse(final Object value, final String pattern) throws ParseException {

    if (value instanceof Number) {
        return value;
    }

    // Note that despite the ambiguous "getInstance" name, and despite the
    // fact that objects returned from this method have the same toString
    // representation, each call to getInstance actually returns a new
    // object.
    final DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);

    // if some constructors default pattern to null, it makes only sense
    // to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            formatter.applyLocalizedPattern(pattern);
        } else {
            formatter.applyPattern(pattern);
        }
    } else {
        log.debug("No pattern provided, using default.");
    }

    return formatter.parse((String) value);
}
项目:siteswap_generator    文件:Siteswap.java   
public Vector<String> toLocalString() {

        Vector<String> localSiteswapStrings = new Vector<String>(mNumberOfJugglers);
        if (mNumberOfJugglers == 1) {
            localSiteswapStrings.add(toString());
            return localSiteswapStrings;
        }

        for(int juggler = 0; juggler < mNumberOfJugglers; ++juggler) {
            String str = new String();
            DecimalFormat formatter = new DecimalFormat("0.#");
            for(int i = 0; i < period_length(); ++i) {
                int position = juggler + i*mNumberOfJugglers;
                str += formatter.format(at(position) / (double) mNumberOfJugglers);
                if (Siteswap.isPass(at(position), mNumberOfJugglers)) {
                    str += "<sub><small>";
                    if (mNumberOfJugglers >= 3)
                        str += Character.toString((char) ('A' + (position + at(position)) % mNumberOfJugglers));
                    if (((juggler + at(position)) / mNumberOfJugglers) % 2 == 0)
                        str += "x";
                    else
                        str += "s";
                    str += "</small></sub>";
                }
                str += "&ensp;";
            }
            localSiteswapStrings.add(str);
        }

        return localSiteswapStrings;

    }
项目:cuttlefish    文件:TikzExporter.java   
/**
 * General constructor for the class, pure object oriented approach.
 * It is necessary to create the object with the network before printing.
 * @param network
 */
public TikzExporter(BrowsableNetwork network){          
    this.network = network;
    colors = new HashMap<Color, String>();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator('.');
    formatter = new DecimalFormat("###.#######", symbols);
    formatter.setGroupingUsed(false);
}
项目:QuranAndroid    文件:TranslationsActivity.java   
@Override
public void onReceive(Context context, Intent intent) {

    //intent from sent broadcast
    float value = intent.getLongExtra(AppConstants.Download.NUMBER, 0);
    float max = intent.getLongExtra(AppConstants.Download.MAX, 0);
    String status = intent.getStringExtra(AppConstants.Download.DOWNLOAD);

    //cases of download
    if (status != null) {
        if (status.equals(AppConstants.Download.IN_DOWNLOAD)) {
            downloadProgress.setMax((int) max);
            downloadProgress.setProgress((int) value);

            DecimalFormat df = new DecimalFormat("#.##");
            String maxDownload = df.format((max / 1000000));
            String currentDownload = df.format((value / 1000000));
            downloadInfo.setText(maxDownload + " " + getString(R.string.mb) + " / " + currentDownload + " " + getString(R.string.mb));
        } else if (status.equals(AppConstants.Download.FAILED)) {
            downloadProgress.setMax(1);
            downloadProgress.setProgress(1);
        } else if (status.equals(AppConstants.Download.SUCCESS)) {
            downloadProgress.setMax(1);
            downloadProgress.setProgress(1);
            progress.dismiss();
            new TafaseerLists().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }else if(status.equals(AppConstants.Download.IN_EXTRACT)){
            downloadProgress.setVisibility(View.GONE);
            downloadInfo.setText(intent.getStringExtra(AppConstants.Download.FILES));
        }
    }
}
项目:LoanCalculator    文件:LoanCalculatorApp.java   
public static void main(String [] args)
{
        DecimalFormat num = new DecimalFormat("#,###.00");
        DecimalFormat interest = new DecimalFormat("##.####");
        LoanCalculator loanCalculator;

        //accept the required input
        String inputString =
                 JOptionPane.showInputDialog("Enter the loan amount");
        double loanAmount = Double.parseDouble(inputString);
        inputString =
                 JOptionPane.showInputDialog("Enter the number of years");
        int numberOfYears = Integer.parseInt(inputString);
        inputString =
                 JOptionPane.showInputDialog("Enter yearly interest rate");
        double yearlyInterestRate = Double.parseDouble(inputString);

        //create LoanCalculator instance
        loanCalculator = new LoanCalculator(loanAmount, numberOfYears,
                                  yearlyInterestRate);

        //display the output
        out.println("Loan amount:          " + num.format(loanAmount));
        out.println("Number of years:      " + numberOfYears);
        out.println("Yearly interest rate: " +
            interest.format(yearlyInterestRate)+ "\n");
        out.println("Monthly payment:      " +
            num.format(loanCalculator.getMonthlyPayment()));
        out.println("Total payment:        " +
            num.format(loanCalculator.getTotalCostOfLoan()));
        out.println("Total interest:       " +
            num.format(loanCalculator.getTotalInterest()));
}
项目:GogoNew    文件:MapsActivity.java   
public String CalculationByDistance(LatLng StartP, LatLng EndP) {
        int Radius = 6371;// radius of earth in Km
        double lat1 = StartP.latitude;
        double lat2 = EndP.latitude;
        double lon1 = StartP.longitude;
        double lon2 = EndP.longitude;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.asin(Math.sqrt(a));
        //double valueResult = Radius * c;
/*double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
        + " Meter   " + meterInDec);*/
        return (new DecimalFormat("##.###").format(Radius * c));
/*double distance = 0;
Location crntLocation = new Location("crntlocation");
crntLocation.setLatitude(StartP.latitude);
crntLocation.setLongitude(StartP.longitude);

Location newLocation = new Location("newlocation");
newLocation.setLatitude(EndP.latitude);
newLocation.setLongitude(EndP.longitude);

distance = crntLocation.distanceTo(newLocation) / 1000;      // in km
return distance;*/
}
项目:Keep-HODLing    文件:BuyEvent.java   
void sendSuccessNotification(double spent, String bought) {
    NumberFormat formatter = new DecimalFormat("#0.00");
    String spentString = formatter.format(spent);

    trackBuy(bought, spentString);

    sendNotification("Bought " + bought + " " + preferences.getCryptoCurrency(), "Paid " + spentString + " " + preferences.getBaseCurrency(), -1);
}