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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: whackpad   File: LenientFormatter.java   Source Code and License 5 votes vote down vote up
FloatUtil(StringBuilder result, FormatToken formatToken,
        DecimalFormat decimalFormat, Object argument) {
    this.result = result;
    this.formatToken = formatToken;
    this.decimalFormat = decimalFormat;
    this.argument = argument;
    this.minusSign = decimalFormat.getDecimalFormatSymbols()
            .getMinusSign();
}
 
Example 42
Project: CGL   File: StatusPrinter.java   Source Code and License 5 votes vote down vote up
private static String getDateString() {
	String out = "";
	NumberFormat formatter = new DecimalFormat("00");
	NumberFormat formatter1 = new DecimalFormat("000");

	int hours = Calendar.getInstance().get(Calendar.HOUR);
	int minutes = Calendar.getInstance().get(Calendar.MINUTE);
	int seconds = Calendar.getInstance().get(Calendar.SECOND);
	int msec = Calendar.getInstance().get(Calendar.MILLISECOND);

	out = formatter.format(hours)+":"+formatter.format(minutes)+":"+formatter.format(seconds)+":"+formatter1.format(msec);
	return out;
}
 
Example 43
Project: parabuild-ci   File: NumberAxis.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a collection of tick units for integer values.
 *
 * @return a collection of tick units for integer values.
 */
public static TickUnitSource createIntegerTickUnits() {

    TickUnits units = new TickUnits();

    units.add(new NumberTickUnit(1,              new DecimalFormat("0")));
    units.add(new NumberTickUnit(2,              new DecimalFormat("0")));
    units.add(new NumberTickUnit(5,              new DecimalFormat("0")));
    units.add(new NumberTickUnit(10,             new DecimalFormat("0")));
    units.add(new NumberTickUnit(20,             new DecimalFormat("0")));
    units.add(new NumberTickUnit(50,             new DecimalFormat("0")));
    units.add(new NumberTickUnit(100,            new DecimalFormat("0")));
    units.add(new NumberTickUnit(200,            new DecimalFormat("0")));
    units.add(new NumberTickUnit(500,            new DecimalFormat("0")));
    units.add(new NumberTickUnit(1000,           new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(2000,           new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(5000,           new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(10000,          new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(20000,          new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(50000,          new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(100000,         new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(200000,         new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(500000,         new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(1000000,        new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(2000000,        new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(5000000,        new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(10000000,       new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(20000000,       new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(50000000,       new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(100000000,      new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(200000000,      new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(500000000,      new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(1000000000,     new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(2000000000,     new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(5000000000.0,   new DecimalFormat("#,##0")));
    units.add(new NumberTickUnit(10000000000.0,  new DecimalFormat("#,##0")));

    return units;

}
 
Example 44
Project: exam   File: ExamSectionQuestion.java   Source Code and License 5 votes vote down vote up
@Transient
@Override
public Double getAssessedScore() {
    switch (question.getType()) {
        case EssayQuestion:
            if (evaluationType == Question.EvaluationType.Points) {
                return essayAnswer == null || essayAnswer.getEvaluatedScore() == null ? 0 :
                        essayAnswer.getEvaluatedScore();
            }
            break;
        case MultipleChoiceQuestion:
            Optional<ExamSectionQuestionOption> o = options.stream()
                    .filter(ExamSectionQuestionOption::isAnswered).findFirst();
            if (o.isPresent()) {
                return o.get().getOption().isCorrectOption() ? maxScore : 0.0;
            }
            break;
        case WeightedMultipleChoiceQuestion:
            Double evaluation = options.stream()
                    .filter(esq -> esq.isAnswered() && esq.getScore() != null)
                    .map(ExamSectionQuestionOption::getScore)
                    .reduce(0.0, (sum, x) -> sum += x);
            // ATM minimum score is zero
            return Math.max(0.0, evaluation);
        case ClozeTestQuestion:
            // sanity check
            if (clozeTestAnswer == null) {
                return 0.0;
            }
            ClozeTestAnswer.Score score = clozeTestAnswer.getScore(this);
            int correct = score.getCorrectAnswers();
            int incorrect = score.getIncorrectAnswers();
            if (correct + incorrect == 0) {
                return 0.0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            return Double.valueOf(df.format(correct * maxScore / (correct + incorrect)));
    }
    return 0.0;
}
 
Example 45
Project: RunMap   File: TrackPresenterImpl.java   Source Code and License 5 votes vote down vote up
public TrackPresenterImpl(){
    mDistanceFormater = (DecimalFormat) NumberFormat.getInstance();
    mDistanceFormater.setMinimumFractionDigits(2);
    mDistanceFormater.setMaximumFractionDigits(2);
    mTimeFormater = (DecimalFormat) DecimalFormat.getInstance();
    mTimeFormater.applyPattern("00");
}
 
Example 46
Project: java-swing-template   File: Utilities.java   Source Code and License 5 votes vote down vote up
public static HashMap<String, String> getGeneratedBillStructureForCustomer(String customer_id, int year, Month month) {
    HashMap<String, String> b_str = new HashMap<>();
    String yrstr = Integer.toString(year);
    if (yrstr.length() == 4) {
        b_str.put("year", yrstr.substring(2, yrstr.length()));
    }
    if (yrstr.length() == 2) {
        b_str.put("year", yrstr);
    }

    b_str.put("month", new DecimalFormat("00").format(month.getMonthNumber() + 1));
    b_str.put("customer_id", customer_id);
    return b_str;
}
 
Example 47
Project: ExPetrum   File: ItemFood.java   Source Code and License 5 votes vote down vote up
@Override
public void addInformation(ItemStack stack, World world, List<String> tooltip, ITooltipFlag advanced)
{
	super.addInformation(stack, world, tooltip, advanced);
	DecimalFormat df = new DecimalFormat("#.#");
	DecimalFormat df1 = new DecimalFormat("#,###");
	tooltip.add(I18n.format("exp.txt.item.desc.rot", df.format((this.getTotalRot(stack) / this.getEntry(stack).getBaseHealth()) * 100)));
	tooltip.add(I18n.format("exp.txt.item.desc.weight", df1.format(this.getTotalWeight(stack))));
}
 
Example 48
Project: avaire   File: UrbanDictionaryCommand.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onCommand(Message message, String[] args) {
    RequestFactory.makeGET("https://api.urbandictionary.com/v0/define")
        .addParameter("term", String.join(" ", args))
        .send((Consumer<Response>) response -> {
            UrbanDictionaryService service = (UrbanDictionaryService) response.toService(UrbanDictionaryService.class);

            if (!service.hasData()) {
                MessageFactory.makeWarning(message, ":user I found nothing for `:query`")
                    .set("query", String.join(" ", args))
                    .queue();
                return;
            }

            UrbanDictionaryService.UrbanDictionary definition = service.getList().get(0);

            double percentage = (((double) definition.getThumbsUp() / definition.getThumbsDown()) * 100) - 100;

            MessageFactory.makeEmbeddedMessage(message.getChannel(), Color.decode("#1D2439"), definition.getDefinition())
                .setTitle(definition.getWord(), definition.getPermalink())
                .addField("Example", definition.getExample(), false)
                .setFooter(String.format("%s%s percentage of people like this. %s\uD83D\uDC4D %s\uD83D\uDC4E",
                    new DecimalFormat("#.##").format(percentage), "%",
                    definition.getThumbsUp(),
                    definition.getThumbsDown()
                )).queue();
        });
    return true;
}
 
Example 49
Project: cuttlefish   File: TikzExporter.java   Source Code and License 5 votes vote down vote up
public TikzExporter() {
	colors = new HashMap<Color, String>();
	DecimalFormatSymbols symbols = new DecimalFormatSymbols(
			Locale.getDefault());
	symbols.setDecimalSeparator('.');
	formatter = new DecimalFormat("###.#######", symbols);
	formatter.setGroupingUsed(false);
	setScalingFactors(defaultNodeSizeFactor, defaultEdgeSizeFactor,
			defaultCoordinateFactor);
}
 
Example 50
Project: kubernetes-elastic-agents   File: Util.java   Source Code and License 5 votes vote down vote up
public static String readableSize(Long memory) {
    Long size = memory * 1024;
    if (size <= 0) return "0";
    final String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB"};
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
 
Example 51
Project: BaseCore   File: ConvertUtils.java   Source Code and License 5 votes vote down vote up
/**
 * String 类型 转 double
 *
 * @param value
 * @return
 */
public static double str2Double(String value) {
    try {
        DecimalFormat df = new DecimalFormat("######0.00");
        return Double.parseDouble(df.format(value));
    } catch (NumberFormatException ex) {
        throw new NumberFormatException();
    }
}
 
Example 52
Project: unitimes   File: DatePatternEditForm.java   Source Code and License 5 votes vote down vote up
public DatePattern getDatePattern(HttpServletRequest request) throws Exception {
	DatePattern dp = null;
	if (getUniqueId()!=null) {
		dp = (new DatePatternDAO()).get(getUniqueId());
		if (dp!=null) dp = (DatePattern)dp.clone();
	}
	if (dp==null) {
		dp = new DatePattern();
	}
	if (dp.getSession()==null) {
		dp.setSession(SessionDAO.getInstance().get(getSessionId()));
	}
	if (request.getParameter("cal_select")!=null) {
		dp.setName(getName());
		dp.setVisible(new Boolean(getVisible()));
		dp.setType(new Integer(getTypeInt()));
		dp.setPatternAndOffset(request);
		if (getNumberOfWeeks() != null && !getNumberOfWeeks().isEmpty()) {
			try {
				DecimalFormat df = new DecimalFormat("0.##", new DecimalFormatSymbols(Localization.getJavaLocale()));
				dp.setNumberOfWeeks(df.parse(getNumberOfWeeks()).floatValue());
			} catch (ParseException e) {
				dp.setNumberOfWeeks(null);
			}
		} else {
			dp.setNumberOfWeeks(null);
		}
	}
	return dp;
}
 
Example 53
Project: Stanford-CP-Course   File: poj_1654.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        int T = 0;
        int digit;
        while ((digit = System.in.read()) != '\n')
            T = (T * 10) + (digit - '0');

        while (T-- > 0) {
            int prevX = 0;
            int prevY = 0;
            long area = 0;
            int ch;
            while ((ch = System.in.read()) != '5') {
                int k = ch - '0';
                int newX = prevX + dx[k];
                int newY = prevY + dy[k];
                area += 1L * (newX + prevX) * (newY - prevY);
                prevX = newX;
                prevY = newY;
            }
            System.in.read(); // burn the \n

            area += -1L * prevX * prevY;
            System.out.println(new DecimalFormat("#.#").format(Math.abs(area) / 2.0));
        }
        
    }
 
Example 54
Project: PA   File: SurvivalUser.java   Source Code and License 5 votes vote down vote up
public void setInfo() {
    DecimalFormat df = new DecimalFormat("#.#");
    ScoreboardUtil board = new ScoreboardUtil(PAData.SURVIVAL.getOldPrefix(), "sur");
    new BukkitRunnable() {
        @Override
        public void run() {
            if (getPlayer() == null || !score) cancel();
            String world;
            switch (getLoc().getWorld().getName()) {
                case "world":
                    world = "§2Survival";
                case "world_nether":
                    world = "§cNether";
                case "world_the_end":
                    world = "§dEnd";
                case "Recursos":
                    world = "§aRecursos";
                case "Eventos":
                    world = "§6Eventos";
                default:
                    world = "§bError";
            }

            board.setName(PAData.SURVIVAL.getOldPrefix());
            board.text(4, "§aDinero: §e" + Double.valueOf(df.format(plugin.getVault().getBalance(getOfflinePlayer()))));
            board.text(3, "§e ");
            board.text(2, "§aMundo: " + world);
            board.text(1, "§e ");
            board.text(0, PACore.getOLD_IP());
            if (getPlayer() != null && score) board.build(getPlayer());
        }
    }.runTaskTimer(plugin, 0, 1);
}
 
Example 55
Project: java-course   File: ValueWrapper.java   Source Code and License 5 votes vote down vote up
/**
 * Returns parsed number.
 * @param number String number representation.
 * @return Parsed number.
 * @throws ParseException Unable to parse given string.
 */
private Number getDecimalNumber(String number) throws ParseException {
	DecimalFormat format = new DecimalFormat();
	DecimalFormatSymbols custom=new DecimalFormatSymbols();
	custom.setDecimalSeparator('.');
	format.setDecimalFormatSymbols(custom);
	return format.parse(number);
}
 
Example 56
Project: CraftyProfessions   File: Database.java   Source Code and License 5 votes vote down vote up
/**************************************************************************
 * Method:      initializeDatabase
 *
 * Description: This method will setup the entire Database if it has
 *              already not been setup. If any errors occur while
 *              executing this method we will return false to notify
 *              the main plugin class that we need to disable the plugin.
 *
 * Parameters:  None
 *
 * Return:
 * @return True  - If the Database gets initialized successfully.
 *         False - If the Database initialization fails at some point.
 *************************************************************************/
public boolean initializeDatabase ()
{
    boolean success;
    long initialTime = System.nanoTime ();
    DecimalFormat timeFormat = new DecimalFormat ("#0.00");

    success = createTables ();

    if (!checkDBExists () && success)
    {
        CraftyProfessions.LogMessage (Level.INFO, DATABASE_PREFIX,
            "Total number of Create Table statements ran: " + mNumTables);

        success = insertIntoTables ();

        if (success)
        {
            CraftyProfessions.LogMessage (Level.INFO, DATABASE_PREFIX,
                "Database has been created and the required data has been inserted!");
        }

        mTotalTimeElapsed = TimeUtil.toSeconds (System.nanoTime () - initialTime);
        CraftyProfessions.LogMessage (Level.INFO, DATABASE_PREFIX,
            "Total time elapsed for database Construction: "
                + timeFormat.format (mTotalTimeElapsed) + "sec");
    }
    else
    {
        CraftyProfessions.LogMessage (Level.INFO, DATABASE_PREFIX, "Database found! Setup not necessary");
    }

    return success;
}
 
Example 57
Project: FuelUp   File: VolumeUtil.java   Source Code and License 5 votes vote down vote up
public static String getFuelVolume(double value) {
    DecimalFormat bddf = new DecimalFormat();
    bddf.setGroupingUsed(false);
    bddf.setMaximumFractionDigits(2);
    bddf.setMinimumFractionDigits(0);

    return bddf.format(value);
}
 
Example 58
Project: EVE   File: Weather.java   Source Code and License 5 votes vote down vote up
public String getTempD4() {
    String temp = "";

    DecimalFormat degree = new DecimalFormat("#.0");
    temp += degree.format(tempD4);
    temp += "\u00b0";
    temp += " " + measurement;

    return temp;
}
 
Example 59
Project: StructPro   File: Structure.java   Source Code and License 5 votes vote down vote up
/**
 * Match roughness acceptability
 * @param surface Region characterizes surface
 * @param bottom Region characterizes bottom
 * @throws IOException If regions are not acceptable
 */
public void matchAccuracy(Region surface, Region bottom) throws IOException {
    DecimalFormat decimal = new DecimalFormat("######0.00");
    double liquidHeight = surface.getAverage() - bottom.getAverage();
    if (getMethod() == Method.AFLOAT) {
        if (surface.getRoughness() > (getHeight() / 3.0 + 2) * Configurator.ACCURACY) {
            throw new IOException("Rough water: " + decimal.format(surface.getRoughness()));
        }
        if (liquidHeight < 6.0) {
            throw new IOException("Too shallow: " + decimal.format(liquidHeight));
        }
    }
    if (getMethod() == Method.UNDERWATER) {
        if (bottom.getRoughness() > (getHeight() / 3.0 + 2) * Configurator.ACCURACY) {
            throw new IOException("Rough bottom: " + decimal.format(bottom.getRoughness()));
        }
        if (liquidHeight < getHeight() * 0.35 && liquidHeight + lift < getHeight()) {
            throw new IOException("Too shallow: " + decimal.format(liquidHeight));
        }
    }
    if (getMethod() == Method.BASIC) {
        if (bottom.getRoughness() > (getHeight() / 8.0 + 2) * Configurator.ACCURACY) {
            throw new IOException("Rough area: " + decimal.format(bottom.getRoughness()));
        }
        if (liquidHeight > 1.5) {
            throw new IOException("Too deep: " + decimal.format(liquidHeight));
        }
    }
}
 
Example 60
Project: Ultraino   File: StringFormats.java   Source Code and License 5 votes vote down vote up
public StringFormats(){
    formatWith4Decs = new DecimalFormat("0.0000");
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    formatWith4Decs.setDecimalFormatSymbols(otherSymbols);
    formatWith2Decs = new DecimalFormat("0.00");
    formatWith2Decs.setDecimalFormatSymbols(otherSymbols);
}