Java Code Examples for java.text.DecimalFormat

The following are top voted examples for showing how to use java.text.DecimalFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: happybot   File: Hypixel.java   View source code 6 votes vote down vote up
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;
}
 
Example 2
Project: acmeair   File: JtlTotals.java   View source code 6 votes vote down vote up
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();
}
 
Example 3
Project: jmt   File: NumberOfCustomersPanel.java   View source code 6 votes vote down vote up
/**
 * @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;
}
 
Example 4
Project: micrometer   File: DoubleFormat.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: MapAnalyst   File: DistortionGrid.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: bean-grid   File: AbstractStringToNumberConverterBean.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 7
Project: htsjdk-s3-plugin   File: PerformanceMonitor.java   View source code 6 votes vote down vote up
/**
 * 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"
    );

}
 
Example 8
Project: openjdk-jdk10   File: Bug6609740.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 9
Project: QN-ACTR-Release   File: NumberOfCustomersPanel.java   View source code 6 votes vote down vote up
/**
 * @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;
}
 
Example 10
Project: unitimes   File: PositionTypes.java   View source code 6 votes vote down vote up
@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;
}
 
Example 11
Project: Zero   File: Utils.java   View source code 6 votes vote down vote up
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)";
        }

    }
 
Example 12
Project: karate   File: Script.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 13
Project: parabuild-ci   File: RelativeDateFormat.java   View source code 6 votes vote down vote up
/**
 * 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");    
}
 
Example 14
Project: parabuild-ci   File: StandardCategoryItemLabelGeneratorTests.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 15
Project: sonar-analyzer-commons   File: LineIssues.java   View source code 6 votes vote down vote up
@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();
}
 
Example 16
Project: ipack   File: NTRUSigningKeyGenerationParameters.java   View source code 6 votes vote down vote up
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();
}
 
Example 17
Project: incubator-netbeans   File: FormatSelector.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: PaySim   File: AggregateParamFileCreator.java   View source code 6 votes vote down vote up
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);
}
 
Example 19
Project: Mobike   File: Utils.java   View source code 6 votes vote down vote up
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 + "公里";
    }
}
 
Example 20
Project: EVideoRecorder   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * 转换文件大小,指定转换的类型
 *
 * @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;
}
 
Example 21
Project: mycat-src-1.6.1-RELEASE   File: TestSelectPerf.java   View source code 6 votes vote down vote up
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) );
}
 
Example 22
Project: ditb   File: OneMeasurementHdrHistogram.java   View source code 6 votes vote down vote up
/**
 * 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)) + "]";
}
 
Example 23
Project: letv   File: GarbageCleanActivity.java   View source code 6 votes vote down vote up
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);
}
 
Example 24
Project: BEAST   File: BEASTCommunicator.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: shareNote   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * 自动判断因该转换的单位
 *
 * @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;
}
 
Example 26
Project: boohee_v5.6   File: DecodedBitStreamParser.java   View source code 5 votes vote down vote up
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));
}
 
Example 27
Project: onprom   File: LogExtractorUsageExample1.java   View source code 5 votes vote down vote up
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. ";
}
 
Example 28
Project: SOS-The-Healthcare-Companion   File: AddReadingActivity.java   View source code 5 votes vote down vote up
@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));
}
 
Example 29
Project: EatDubbo   File: PerformanceUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 30
Project: oscm   File: PriceConverter.java   View source code 5 votes vote down vote up
@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;
}
 
Example 31
Project: uavstack   File: DiskIOCollector.java   View source code 5 votes vote down vote up
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
        }
    }
 
Example 32
Project: Endless   File: Stats.java   View source code 5 votes vote down vote up
@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();
}
 
Example 33
Project: Persephone   File: MetricsCacheGridRow.java   View source code 5 votes vote down vote up
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());
}
 
Example 34
Project: NotifyTools   File: DecimalLocaleConverter.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 35
Project: siteswap_generator   File: Siteswap.java   View source code 5 votes vote down vote up
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;
		
	}
 
Example 36
Project: cuttlefish   File: TikzExporter.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 37
Project: QuranAndroid   File: TranslationsActivity.java   View source code 5 votes vote down vote up
@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));
        }
    }
}
 
Example 38
Project: LoanCalculator   File: LoanCalculatorApp.java   View source code 5 votes vote down vote up
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()));
}
 
Example 39
Project: GogoNew   File: MapsActivity.java   View source code 5 votes vote down vote up
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;*/
}
 
Example 40
Project: Keep-HODLing   File: BuyEvent.java   View source code 5 votes vote down vote up
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);
}