下面列出了java.text.DecimalFormat#applyPattern ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public NumberFormat getNumberFormat(Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale);
if (!(format instanceof DecimalFormat)) {
if (this.pattern != null) {
throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format);
}
return format;
}
DecimalFormat decimalFormat = (DecimalFormat) format;
decimalFormat.setParseBigDecimal(true);
if (this.pattern != null) {
decimalFormat.applyPattern(this.pattern);
}
return decimalFormat;
}
private String getDecoratedStringFromNumber(long number)
{
String numberPattern = "#,###,###,###";
String decoStr = "";
DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
if (_showCommas && !_showCurrency)
formatter.applyPattern(numberPattern);
else if (_showCommas && _showCurrency)
formatter.applyPattern(_currencySymbol + " " + numberPattern);
else if (!_showCommas && _showCurrency)
formatter.applyPattern(_currencySymbol + " ");
else if (!_showCommas && !_showCurrency)
{
decoStr = number + "";
return decoStr;
}
decoStr = formatter.format(number);
return decoStr;
}
@Override
public NumberFormat getNumberFormat(Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale);
if (!(format instanceof DecimalFormat)) {
if (this.pattern != null) {
throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format);
}
return format;
}
DecimalFormat decimalFormat = (DecimalFormat) format;
decimalFormat.setParseBigDecimal(true);
if (this.pattern != null) {
decimalFormat.applyPattern(this.pattern);
}
return decimalFormat;
}
public void write(PrintWriter printer, TimeSeries series) {
Locale locale = new Locale("en", "US");
DecimalFormat formatter = (DecimalFormat)NumberFormat.getNumberInstance(locale);
formatter.applyPattern("0.0000######");
printer.print(String.format(header, series.getProperty("sensorid"), series.getLocation(), series.getProperty("position"), series.getSource(), series.getQuantityId(), series.getUnitId(), series.getProperty("use") ));
final double times[] = series.getTimesRef();
final double values[] = series.getValuesRef();
//TODO: detect order on read and use this order
printer.println("datetime;value");
String dateString;
for (int i = 0; i < times.length; i++) {
dateString = TimeUtils.mjdToString( times[i],this.datePattern);
printer.println( dateString + this.delimiter + formatter.format(values[i]) );
}
printer.flush();
}
@Override void apply(DecimalFormat decimalFormat) {
/* To switch to using codes from symbols, we replace each single occurrence of the
* currency-sign character with two such characters in a row.
* We also insert a space character between every occurence of this character and an
* adjacent numerical digit or negative sign (that is, between the currency-sign and
* the signed-number). */
decimalFormat.applyPattern(
negify(decimalFormat.toPattern()).replaceAll("¤","¤¤").
replaceAll("([#0.,E-])¤¤","$1 ¤¤").
replaceAll("¤¤([0#.,E-])","¤¤ $1")
);
}
/**
* bytes转换mb
*
* @param sizeInBytes 容量大小
* @return mb
*/
public static float getSizeInMB(long sizeInBytes) {
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
df.applyPattern("0.0");
String result = df.format((float) sizeInBytes / 1024 / 1024);
Log.e(TAG, "getSizeInMB: " + result);
result = result.replaceAll(",", "."); // in some case , 0.0 will be 0,0
return Float.valueOf(result);
}
public static float getSizeInMB(long sizeInBytes) {
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
df.applyPattern("0.0");
String result = df.format((float) sizeInBytes / 1024 / 1024);
Log.e(TAG, "getSizeInMB: " + result);
result = result.replaceAll(",", "."); // in some case , 0.0 will be 0,0
return Float.valueOf(result);
}
public static String getFileSizeMb(File file) {
try {
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
df.applyPattern("0.0#");
long fileSizeInBytes = file.length();
return df.format(fileSizeInBytes / (1024.0f * 1024.0f)) + " MiB";
} catch (Exception e) {
return "<null>";
}
}
static String fweshort(double x)
// a shorter version of fwe()
{
NumberFormat nf = NumberFormat.getInstance(Locale.US);
DecimalFormat ef = (DecimalFormat) nf;
ef.applyPattern("0.00E0");
String s = ef.format(x);
return s; // else negative
}
@Override
void apply(DecimalFormat decimalFormat) {
/* To switch to using codes from symbols, we replace each single occurrence of the
* currency-sign character with two such characters in a row.
* We also insert a space character between every occurence of this character and an
* adjacent numerical digit or negative sign (that is, between the currency-sign and
* the signed-number). */
decimalFormat.applyPattern(
negify(decimalFormat.toPattern()).replaceAll("¤", "¤¤").
replaceAll("([#0.,E-])¤¤", "$1 ¤¤").
replaceAll("¤¤([0#.,E-])", "¤¤ $1")
);
}
/**
* 处理金额显示千分位的问题
* @param moneyValueStr
* @return
*/
public static String parseMoney(String moneyValueStr){
DecimalFormat a = new DecimalFormat("");
Double dd = Double.parseDouble(moneyValueStr);
String pattern="' '###,###.##' ';''###,###.##''";
a.applyPattern(pattern);
return a.format(dd).trim();
}
/**
* Creates an object (<code>DecimalFormat</code>) based on this description.
*
* @return The object.
*/
public Object createObject() {
final DecimalFormat format = (DecimalFormat) super.createObject();
if ( getParameter( "pattern" ) != null ) {
format.applyPattern( (String) getParameter( "pattern" ) );
}
// if (getParameter("localizedPattern") != null) {
// format.applyLocalizedPattern((String) getParameter("localizedPattern"));
// }
return format;
}
/**
* @param numberPattern
* the input number pattern of the type "####"
* @return the {@link DecimalFormat} with the applied pattern
*/
private DecimalFormat formatter(String numberPattern) {
DecimalFormat retVal = new DecimalFormat();
try {
if (StringUtils.isNotBlank(numberPattern)) {
retVal.applyPattern(numberPattern.replaceAll("#", "0"));
return retVal;
}
} catch (IllegalArgumentException iae) {
LOG.error(String.format("Error applying pattern %s", numberPattern), iae);
}
retVal.applyPattern("00000");
return retVal;
}
/**
* Source: http://www.luschny.de/java/doubleformat.html
*
* @param dValue
* the value to be formatted
* @param nScale
* The precision of the decimal scale. If type is
* {@link EDecimalType#FIX} the decimal scale, else the (carrying scale
* - 1). Should be ≥ 0.
* @param eType
* The formatting type. May not be <code>null</code>.
* @param aLocale
* The locale to be used for the decimal symbols. May not be
* <code>null</code>.
* @return the string representation of the double value. For NaN and infinite
* values, the return of {@link Double#toString()} is returned.
*/
@Nonnull
public static String getFormatted (final double dValue,
@Nonnegative final int nScale,
@Nonnull final EDecimalType eType,
@Nonnull final Locale aLocale)
{
ValueEnforcer.isGE0 (nScale, "Scale");
ValueEnforcer.notNull (eType, "Type");
ValueEnforcer.notNull (aLocale, "Locale");
if (Double.isNaN (dValue) || Double.isInfinite (dValue))
return Double.toString (dValue);
// Avoid negative scales
final DecimalFormat aDF = (DecimalFormat) NumberFormat.getInstance (aLocale);
aDF.setDecimalFormatSymbols (DecimalFormatSymbols.getInstance (aLocale));
aDF.setMaximumFractionDigits (nScale);
aDF.setMinimumFractionDigits (nScale);
if (eType.isExponential ())
{
String sPattern = "0E0";
if (nScale > 0)
sPattern += '.' + StringHelper.getRepeated ('0', nScale);
aDF.applyPattern (sPattern);
}
else
{
aDF.setGroupingUsed (false);
aDF.setMinimumIntegerDigits (1);
}
return aDF.format (dValue);
}
private static String formatToScientific(Double d) {
BigDecimal input = BigDecimal.valueOf(d).stripTrailingZeros();
int precision = input.scale() < 0
? input.precision() - input.scale()
: input.precision();
StringBuilder s = new StringBuilder("0.0");
for (int i = 2; i < precision; i++) {
s.append("#");
}
s.append("E0");
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern(s.toString());
return df.format(d);
}
@Override void apply(DecimalFormat decimalFormat) {
/* To switch to using codes from symbols, we replace each single occurrence of the
* currency-sign character with two such characters in a row.
* We also insert a space character between every occurence of this character and an
* adjacent numerical digit or negative sign (that is, between the currency-sign and
* the signed-number). */
decimalFormat.applyPattern(
negify(decimalFormat.toPattern()).replaceAll("¤","¤¤").
replaceAll("([#0.,E-])¤¤","$1 ¤¤").
replaceAll("¤¤([0#.,E-])","¤¤ $1")
);
}
public static double str2num( String pattern, String decimal, String grouping, String currency, String value ) throws HopValueException {
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat) nf;
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
if ( !Utils.isEmpty( pattern ) ) {
df.applyPattern( pattern );
}
if ( !Utils.isEmpty( decimal ) ) {
dfs.setDecimalSeparator( decimal.charAt( 0 ) );
}
if ( !Utils.isEmpty( grouping ) ) {
dfs.setGroupingSeparator( grouping.charAt( 0 ) );
}
if ( !Utils.isEmpty( currency ) ) {
dfs.setCurrencySymbol( currency );
}
try {
df.setDecimalFormatSymbols( dfs );
return df.parse( value ).doubleValue();
} catch ( Exception e ) {
String message = "Couldn't convert string to number " + e.toString();
if ( !isEmpty( pattern ) ) {
message += " pattern=" + pattern;
}
if ( !isEmpty( decimal ) ) {
message += " decimal=" + decimal;
}
if ( !isEmpty( grouping ) ) {
message += " grouping=" + grouping.charAt( 0 );
}
if ( !isEmpty( currency ) ) {
message += " currency=" + currency;
}
throw new HopValueException( message );
}
}
/**
* @param d 要格式化的数字
* @param parttern 要求格式结果,例如:0.00
* @return
*/
public static String formatNum(double d, String parttern) {
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyPattern(parttern);
return df.format(d);
}
public static String numberFormat(Object object, String format) {
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern(format);
return myformat.format(object);
}
protected void echoGraphData(PrintWriter writer) {
writer.println("<Data>");
// Nodes
Collection<DataNode> nodeColl = dataNodes.values();
int maxArea = nodeColl.size() * 2;
if(maxArea > 5000)
{
maxArea = 5000;
}
ArrayList<DataNode> nodeList = new ArrayList<DataNode>(dataNodes.values());
Collections.sort(nodeList, new sortByNodeId());
// Lets make just a simple grid, nothing fancy.
double nodesPerLine = Math.floor(Math.sqrt(nodeColl.size()));
double lineXCounter = 1;
double lineYCounter = 1;
//for (DataNode dataNode : nodeColl) {
for (int i=0;i<nodeList.size();i++) {
DataNode dataNode = nodeList.get(i);
double randomX = (maxArea/2)-maxArea*(lineXCounter/nodesPerLine);
double randomY = (maxArea/2)-maxArea*(lineYCounter/nodesPerLine);
lineXCounter++;
if(lineXCounter >= nodesPerLine){
lineXCounter = 1;
lineYCounter++;
}
//randomX = (i+1)*2;
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat formatter = (DecimalFormat)nf;
formatter.applyPattern("#.##");
String ranX = formatter.format(randomX);
String ranY = formatter.format(randomY);
println(writer, "<nodedata nodepre=\""+dataNode.pre+"\">");
println(writer, "<position x=\""+ranX+"\" y=\""+ranY+"\" z=\"0.0\"/>");
if(dataNode.isDummy) {
println(writer, "<color a=\"1.0\" b=\"0.7\" g=\"0.7\" r=\"0.7\"/>");
} else {
println(writer, "<color a=\"1.0\" b=\"0.61568628\" g=\"0.39411766\" r=\"0.31176471\"/>");
}
println(writer, "<size value=\"5.0\"/>");
println(writer, "</nodedata>");
}
// Edges
//for (DataEdge dataEdge : dataEdges) {
for (int i=0;i<dataEdges.size();i++) {
DataEdge dataEdge = dataEdges.get(i);
println(writer, "<edgedata sourcepre=\""+dataEdge.node1.pre+"\" targetpre=\""+dataEdge.node2.pre+"\">");
println(writer, "<color a=\"1.0\" b=\"0.0\" g=\"0.0\" r=\"-1.0\"/>");
println(writer, "</edgedata>");
}
writer.println("</Data>");
}