本文整理汇总了Java中java.text.DecimalFormat类的典型用法代码示例。如果您正苦于以下问题:Java DecimalFormat类的具体用法?Java DecimalFormat怎么用?Java DecimalFormat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DecimalFormat类属于java.text包,在下文中一共展示了DecimalFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getAllFields
import java.text.DecimalFormat; //导入依赖的package包/类
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;
}
示例2: cntByTimeString
import java.text.DecimalFormat; //导入依赖的package包/类
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();
}
示例3: getValueAtImpl
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* @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;
}
示例4: initialValue
import java.text.DecimalFormat; //导入依赖的package包/类
@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;
}
示例5: getErrorMessageForIncorrectNumberOfGridLines
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* 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;
}
示例6: getFormat
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* 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));
}
示例7: printSummary
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* 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"
);
}
示例8: parseOnPattern
import java.text.DecimalFormat; //导入依赖的package包/类
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);
}
}
示例9: getValueAtImpl
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* @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;
}
示例10: load
import java.text.DecimalFormat; //导入依赖的package包/类
@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;
}
示例11: bytes2String
import java.text.DecimalFormat; //导入依赖的package包/类
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)";
}
}
示例12: convertToBigDecimal
import java.text.DecimalFormat; //导入依赖的package包/类
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;
}
}
示例13: RelativeDateFormat
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* 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");
}
示例14: testGenerateLabel
import java.text.DecimalFormat; //导入依赖的package包/类
/**
* 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);
}
示例15: toString
import java.text.DecimalFormat; //导入依赖的package包/类
@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();
}