下面列出了java.text.DecimalFormat#setDecimalFormatSymbols ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static NumberFormat newFormatter(boolean sampler) {
// Always create the formatter for the US locale in order to avoid this bug:
// https://github.com/indeedeng/java-dogstatsd-client/issues/3
NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
numberFormatter.setGroupingUsed(false);
// 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);
}
if (sampler) {
numberFormatter.setMinimumFractionDigits(6);
} else {
numberFormatter.setMaximumFractionDigits(6);
}
return numberFormatter;
}
public static String round(String value, int places) {
try {
String pattern = "0.";
if (places == 0) pattern += "#";
else {
for (int i = 0; i < places; i++) {
pattern += "#";
}
}
DecimalFormat decimalFormat = new DecimalFormat(pattern);
decimalFormat.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
return decimalFormat.format(new BigDecimal(value));
} catch (Exception e) { //complex number
return value;
}
}
public BigDecimal getAmount() {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true);
df.setDecimalFormatSymbols(symbols);
df.setParseBigDecimal(true);
try {
String s = edAmount.getText().toString();
if (s.equals("")) {
s = "0";
}
return ((BigDecimal) df.parse(s.replaceAll(" ", ""))).setScale(2, RoundingMode.HALF_UP);
} catch (NumberFormatException | ParseException nfe) {
return BigDecimal.ZERO;
}
}
public static String getLocalizedAmountNoDecimals(final BigDecimal truncated, final Currency currency) {
final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(currency.getDecimalSeparator());
dfs.setGroupingSeparator(currency.getThousandsSeparator());
final DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(dfs);
df.setMinimumFractionDigits(0);
df.setMaximumFractionDigits(0);
return df.format(truncated);
}
private DecimalFormat buildFormatWithSpaceGroupingSeparator() {
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
decimalFormat.setDecimalFormatSymbols(symbols);
return decimalFormat;
}
public Budget(String name, float currAmount, float limitAmount, int color) {
mName = name;
mCurrAmount = currAmount;
mLimitAmount = limitAmount;
mColor = color;
mFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
DecimalFormatSymbols symbols = mFormatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
mFormatter.setDecimalFormatSymbols(symbols);
mCurrencyFormatter = NumberFormat.getCurrencyInstance();
}
/**
* Returns a thousans separated decimar formatter.
*
* @return
*/
public static DecimalFormat getThousandSeperatedDecimalFormat() {
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
return df;
}
protected DecimalFormat format() {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
df.setMinimumFractionDigits(3);
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
dfs.setDecimalSeparator((new String(".").charAt(0)));
df.setDecimalFormatSymbols(dfs);
df.setGroupingSize(20);
return df;
}
/** Print the matrix to the output stream. Line the elements up in
* columns with a Fortran-like 'Fw.d' style format.
@param output Output stream.
@param w Column width.
@param d Number of digits after the decimal.
*/
public void print (PrintWriter output, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
print(output,format,w+2);
}
/**
* Adds a DecimalFormat object to the _formatSymbols map.
* The entry is created with the input DecimalFormatSymbols.
*/
public void addDecimalFormat(String name, DecimalFormatSymbols symbols) {
// Instanciate map for formatting symbols if needed
if (_formatSymbols == null) _formatSymbols = new HashMap<>();
// The name cannot be null - use empty string instead
if (name == null) name = EMPTYSTRING;
// Construct a DecimalFormat object containing the symbols we got
final DecimalFormat df = new DecimalFormat();
if (symbols != null) {
df.setDecimalFormatSymbols(symbols);
}
_formatSymbols.put(name, df);
}
public Bill(String name, float amount, Date dueDate, int color) {
mName = name;
mAmount = amount;
mDueDate = dueDate;
mColor = color;
mFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
DecimalFormatSymbols symbols = mFormatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
mFormatter.setDecimalFormatSymbols(symbols);
}
/**
* Print the matrix to the output stream. Line the elements up in columns with a Fortran-like 'Fw.d' style format.
*
* @param output Output stream.
* @param w Column width.
* @param d Number of digits after the decimal.
*/
public void print(final PrintWriter output, final int w, final int d) {
final DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
print(output, format, w + 2);
}
public void test_equals() {
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormat cloned = (DecimalFormat) format.clone();
cloned.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
assertEquals(format, cloned);
Currency c = Currency.getInstance(Locale.US);
cloned.setCurrency(c);
assertEquals(format, cloned);
}
/**
* Print the matrix to the output stream. Line the elements up in columns
* with a Fortran-like 'Fw.d' style format.
*
* @param output Output stream.
* @param w dataolumn width.
* @param d Number of digits after the decimal.
*/
public synchronized void print(PrintWriter output, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
print(output, format, w + 2);
}
public Double getAverageSubmittedAssessmentGrading(final Long publishedAssessmentId, final String agentId) {
Double averageScore = 0.0;
AssessmentGradingData ag = null;
final HibernateCallback<List<AssessmentGradingData>> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by a.submittedDate desc");
q.setLong("id", publishedAssessmentId);
q.setString("agent", agentId);
q.setBoolean("forgrade", true);
q.setInteger("status", AssessmentGradingData.REMOVED);
return q.list();
};
List<AssessmentGradingData> assessmentGradings = getHibernateTemplate().execute(hcb);
if (!assessmentGradings.isEmpty()) {
AssessmentGradingData agd;
Double cumulativeScore = new Double(0);
Iterator i = assessmentGradings.iterator();
while (i.hasNext()) {
agd = (AssessmentGradingData) i.next();
cumulativeScore += agd.getFinalScore();
}
averageScore = cumulativeScore / assessmentGradings.size();
DecimalFormat df = new DecimalFormat("0.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
averageScore = new Double(df.format((double) averageScore));
}
return averageScore;
}
/**
* Adds a DecimalFormat object to the _formatSymbols map.
* The entry is created with the input DecimalFormatSymbols.
*/
public void addDecimalFormat(String name, DecimalFormatSymbols symbols) {
// Instanciate map for formatting symbols if needed
if (_formatSymbols == null) _formatSymbols = new HashMap<>();
// The name cannot be null - use empty string instead
if (name == null) name = EMPTYSTRING;
// Construct a DecimalFormat object containing the symbols we got
final DecimalFormat df = new DecimalFormat();
if (symbols != null) {
df.setDecimalFormatSymbols(symbols);
}
_formatSymbols.put(name, df);
}
public NumberTextWatcher(EditText et, TextWatcher textWatcher) {
mTextWatcher = textWatcher;
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true);
df.setDecimalFormatSymbols(symbols);
dfnd = new DecimalFormat("#,###");
dfnd.setDecimalFormatSymbols(symbols);
this.et = et;
hasFractionalPart = false;
}
public static String formatNum(double number, String formatString) {
final DecimalFormat format = new DecimalFormat(formatString);
format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(number);
}
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 );
}
}
/**
* Build the base part of the url (doesn't change for getMap or getFeatureInfo requests).
*
* @param targetUrl
* base url
* @param width
* image width
* @param height
* image height
* @param box
* bounding box
* @return base WMS url
* @throws GeomajasException
* missing parameter
*/
private StringBuilder formatBaseUrl(String targetUrl, int width, int height, Bbox box) throws GeomajasException {
try {
StringBuilder url = new StringBuilder(targetUrl);
int pos = url.lastIndexOf("?");
if (pos > 0) {
url.append("&SERVICE=WMS");
} else {
url.append("?SERVICE=WMS");
}
String layers = getId();
if (layerInfo.getDataSourceName() != null) {
layers = layerInfo.getDataSourceName();
}
url.append("&layers=");
url.append(URLEncoder.encode(layers, "UTF8"));
url.append("&WIDTH=");
url.append(Integer.toString(width));
url.append("&HEIGHT=");
url.append(Integer.toString(height));
DecimalFormat decimalFormat = new DecimalFormat(); // create new as this is not thread safe
decimalFormat.setDecimalSeparatorAlwaysShown(false);
decimalFormat.setGroupingUsed(false);
decimalFormat.setMinimumFractionDigits(0);
decimalFormat.setMaximumFractionDigits(100);
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
decimalFormat.setDecimalFormatSymbols(symbols);
url.append("&bbox=");
url.append(decimalFormat.format(box.getX()));
url.append(",");
url.append(decimalFormat.format(box.getY()));
url.append(",");
url.append(decimalFormat.format(box.getMaxX()));
url.append(",");
url.append(decimalFormat.format(box.getMaxY()));
url.append("&format=");
url.append(format);
url.append("&version=");
url.append(version);
if ("1.3.0".equals(version)) {
url.append("&crs=");
} else {
url.append("&srs=");
}
url.append(URLEncoder.encode(layerInfo.getCrs(), "UTF8"));
url.append("&styles=");
url.append(styles);
if (null != parameters) {
for (Parameter p : parameters) {
url.append("&");
url.append(URLEncoder.encode(p.getName(), "UTF8"));
url.append("=");
url.append(URLEncoder.encode(p.getValue(), "UTF8"));
}
}
if (useProxy && null != securityContext.getToken()) {
url.append("&userToken=");
url.append(securityContext.getToken());
}
return url;
} catch (UnsupportedEncodingException uee) {
throw new IllegalStateException("Cannot find UTF8 encoding?", uee);
}
}