Java 类java.text.NumberFormat 实例源码
项目:lams
文件:NumberUtil.java
/**
* Convert a string back into a Float. Assumes string was formatted using formatLocalisedNumber originally. Should
* ensure that it is using the same locale/number format as when it was formatted. If no locale is suppied, it will
* use the server's locale.
*
* Need to strip out any spaces as spaces are valid group separators in some European locales (e.g. Polish) but they
* seem to come back from Firefox as a plain space rather than the special separating space.
*/
public static Double getLocalisedDouble(String inputStr, Locale locale) {
String numberStr = inputStr;
if (numberStr != null) {
numberStr = numberStr.replace(" ", "");
}
if ((numberStr != null) && (numberStr.length() > 0)) {
Locale useLocale = locale != null ? locale : NumberUtil.getServerLocale();
NumberFormat format = NumberFormat.getInstance(useLocale);
ParsePosition pp = new ParsePosition(0);
Number num = format.parse(numberStr, pp);
if ((num != null) && (pp.getIndex() == numberStr.length())) {
return num.doubleValue();
}
}
throw new NumberFormatException("Unable to convert number " + numberStr + "to double using locale "
+ locale.getCountry() + " " + locale.getLanguage());
}
项目:openjdk-jdk10
文件:Bug6278616.java
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getInstance();
for (int j = 0; j < ints.length; j++) {
String s_i = nf.format(ints[j]);
String s_ai = nf.format(new AtomicInteger(ints[j]));
if (!s_i.equals(s_ai)) {
throw new RuntimeException("format(AtomicInteger " + s_ai +
") doesn't equal format(Integer " +
s_i + ")");
}
}
for (int j = 0; j < longs.length; j++) {
String s_l = nf.format(longs[j]);
String s_al = nf.format(new AtomicLong(longs[j]));
if (!s_l.equals(s_al)) {
throw new RuntimeException("format(AtomicLong " + s_al +
") doesn't equal format(Long " +
s_l + ")");
}
}
}
项目:DateTimePicker
文件:SimpleMonthView.java
private void attrHandler(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final Resources res = context.getResources();
mDesiredMonthHeight = res.getDimensionPixelSize(R.dimen.date_picker_month_height);
mDesiredDayOfWeekHeight = res.getDimensionPixelSize(R.dimen.date_picker_day_of_week_height);
mDesiredDayHeight = res.getDimensionPixelSize(R.dimen.date_picker_day_height);
mDesiredCellWidth = res.getDimensionPixelSize(R.dimen.date_picker_day_width);
mDesiredDaySelectorRadius = res.getDimensionPixelSize(
R.dimen.date_picker_day_selector_radius);
// Set up accessibility components.
mTouchHelper = new MonthViewTouchHelper(this);
ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
mLocale = res.getConfiguration().locale;
mCalendar = Calendar.getInstance(mLocale);
mDayFormatter = NumberFormat.getIntegerInstance(mLocale);
updateMonthYearLabel();
updateDayOfWeekLabels();
initPaints(res);
}
项目:AgentWorkbench
文件:SystemLoadPanel.java
/**
* Sets the number of agents.
* @param noAgents the new number of agents
*/
public void setNumberOfAgents(Integer noAgents) {
String displayText = null;
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumIntegerDigits(5);
nf.setMaximumIntegerDigits(5);
nf.setGroupingUsed(false);
if (noAgents==null) {
displayText = " " + nf.format(0) + " " + Language.translate("Agenten") + " ";
} else {
displayText = " " + nf.format(noAgents) + " " + Language.translate("Agenten") + " ";
}
jLabelAgentCount.setText(displayText);
}
项目:geomapapp
文件:GeneralUtils.java
/**
* determine number of decimal places to display latitude and longitude,
* based on the zoom level.
* @param zoom
* @return
*/
public static NumberFormat getNumberFormat(double zoom) {
NumberFormat fmt = NumberFormat.getInstance();
if ( zoom < 16 ) {
fmt.setMaximumFractionDigits(2);
fmt.setMinimumFractionDigits(2);
}
else if ( zoom >= 16 && zoom < 256 ) {
fmt.setMaximumFractionDigits(3);
fmt.setMinimumFractionDigits(3);
}
else if ( zoom >= 256 && zoom < 4096 ) {
fmt.setMaximumFractionDigits(4);
fmt.setMinimumFractionDigits(4);
}
else if ( zoom >= 4096 && zoom < 32768 ) {
fmt.setMaximumFractionDigits(5);
fmt.setMinimumFractionDigits(5);
}
else if ( zoom >= 32768 ) {
fmt.setMaximumFractionDigits(6);
fmt.setMinimumFractionDigits(6);
}
return fmt;
}
项目:VanillaPlus
文件:Currency.java
public Currency(int id, ConfigurationSection section, MComponentManager manager){
this.id = id;
this.name = manager.get(section.getString(Node.NAME.get()));
this.single = manager.get(section.getString("SINGLE"));
this.alias = section.getString("ALIAS");
int type = section.getInt("FORMAT_TYPE", 0);
this.format = (DecimalFormat) NumberFormat.getNumberInstance( type == 0 ? Locale.GERMAN : type == 1 ? Locale.ENGLISH : Locale.FRENCH);
format.applyPattern(section.getString("FORMAT", "###,###.### "));
this.step = section.getDouble("STEP", 0.001);
double temp = ((int)(step*1000))/1000.0;
if(step < 0.001 || temp != step)
ErrorLogger.addError("Invalid step amount : " + step);
this.min = ((int)section.getDouble("MIN", 0)/step)*step;
this.max = ((int)section.getDouble("MAX", 9999999999.999)/step)*step;
this.allowPay = section.getBoolean("ALLOW_PAY", false);
this.useServer = section.getBoolean("USE_SERVER", false);
this.booster = 1.0;
}
项目:parabuild-ci
文件:MeterPlot.java
/**
* Creates a new plot that displays the value from the supplied dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*/
public MeterPlot(ValueDataset dataset) {
super();
this.shape = DialShape.CIRCLE;
this.meterAngle = DEFAULT_METER_ANGLE;
this.range = new Range(0.0, 100.0);
this.tickSize = 10.0;
this.tickPaint = Color.white;
this.units = "Units";
this.needlePaint = MeterPlot.DEFAULT_NEEDLE_PAINT;
this.tickLabelsVisible = true;
this.tickLabelFont = MeterPlot.DEFAULT_LABEL_FONT;
this.tickLabelPaint = Color.black;
this.tickLabelFormat = NumberFormat.getInstance();
this.valueFont = MeterPlot.DEFAULT_VALUE_FONT;
this.valuePaint = MeterPlot.DEFAULT_VALUE_PAINT;
this.dialBackgroundPaint = MeterPlot.DEFAULT_DIAL_BACKGROUND_PAINT;
this.intervals = new java.util.ArrayList();
setDataset(dataset);
}
项目:HackerRank-Studies
文件:Solution.java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();
// use NumberFormat class by built-in Locale
String us = NumberFormat.getCurrencyInstance(Locale.US).format(payment);
String china = NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment);
String france = NumberFormat.getCurrencyInstance(Locale.FRANCE).format(payment);
// India does not have a built-in Locale
String india = NumberFormat.getCurrencyInstance(new Locale("en","in")).format(payment);
System.out.println("US: " + us);
System.out.println("India: " + india);
System.out.println("China: " + china);
System.out.println("France: " + france);
}
项目:jdk8u-jdk
文件:FormatMicroBenchmark.java
private static String benchFormatFair(NumberFormat nf) {
String str = "";
double k = 1000.0d / (double) MAX_RANGE;
k *= k;
double d;
double absj;
double jPowerOf2;
for (int j = - MAX_RANGE; j <= MAX_RANGE; j++) {
absj = (double) j;
jPowerOf2 = absj * absj;
d = k * jPowerOf2;
if (j < 0) d = -d;
str = nf.format(d);
}
return str;
}
项目:OpenDA
文件:ASCIIVectorIoObject.java
@Override
public void finish() {
//write values to file
PrintWriter fo = null;
NumberFormat format = NumberFormat.getInstance(Locale.US);
try {
fo = new PrintWriter(new FileOutputStream(myFile));
double[] values = this.myExchangeItem.getValuesAsDoubles();
for (int i=0; i<values.length; i++) {
String s = String.format(Locale.US, "%f", values[i]);
fo.println(s);
}
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
项目:ACE_HackerRank
文件:Solution.java
public static void main(String[] args) {
/* Save input */
Scanner scan = new Scanner(System.in);
double payment = scanner.nextDouble();
scan.close();
/* Create custom Locale for India - I used the "IANA Language Subtag Registry" to find India's country code */
Locale indiaLocale = new Locale("en", "IN");
/* Create NumberFormats using Locales */
NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat india = NumberFormat.getCurrencyInstance(indiaLocale);
NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);
/* Print output */
System.out.println("US: " + us.format(payment));
System.out.println("India: " + india.format(payment));
System.out.println("China: " + china.format(payment));
System.out.println("France: " + france.format(payment));
}
项目:swage
文件:DoubleFormatTest.java
private void test(double val) throws Exception {
// Should behave exactly the same as standard number format
// with no extra trailing zeros, six max trailing zeros.
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(6);
nf.setGroupingUsed(false);
String expected = nf.format(val);
StringBuilder sb = new StringBuilder();
DoubleFormat.format(sb, val);
assertEquals(expected, sb.toString());
}
项目:aliyun-maxcompute-data-collectors
文件:PerfCounters.java
/**
* @return a string of the form "xxxx bytes" or "xxxxx KB" or "xxxx GB",
* scaled as is appropriate for the current value.
*/
private String formatBytes() {
double val;
String scale;
if (bytes > ONE_GB) {
val = (double) bytes / (double) ONE_GB;
scale = "GB";
} else if (bytes > ONE_MB) {
val = (double) bytes / (double) ONE_MB;
scale = "MB";
} else if (bytes > ONE_KB) {
val = (double) bytes / (double) ONE_KB;
scale = "KB";
} else {
val = (double) bytes;
scale = "bytes";
}
NumberFormat fmt = NumberFormat.getInstance();
fmt.setMaximumFractionDigits(MAX_PLACES);
return fmt.format(val) + " " + scale;
}
项目:baud
文件:BaudEntryDay.java
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(4);
nf.setGroupingUsed(false);
StringBuilder sb = new StringBuilder();
sb.append("Date: ").append(date.format(formatter)).append(", ");
sb.append("Total NAV: ").append(nf.format(totalNav)).append(", ");
sb.append("Share price: ").append(nf.format(sharePrice)).append(", ");
sb.append("Total shares: ").append(nf.format(getTotalShares()));
return sb.toString();
}
项目:incubator-netbeans
文件:LockCCTNode.java
public void debug() {
if (parent != null) {
String offset = "";
for (CCTNode p = parent; p != null; p = p.getParent()) {
offset += " ";
}
System.out.println(offset + getNodeName() +
" Waits: " + getWaits() +
" Time: " + getTime() +
" " + NumberFormat.getPercentInstance().format(getTimeInPerCent()/100));
}
for (CCTNode ch : getChildren()) {
if (ch instanceof LockCCTNode) {
((LockCCTNode) ch).debug();
}
}
}
项目:dble
文件:ItemFuncFormat.java
@Override
public String valStr() {
int pl = args.get(1).valInt().intValue();
if (pl < 0)
pl = 0;
String local = "en_US";
if (args.size() == 3)
local = args.get(2).valStr();
Locale loc = new Locale(local);
NumberFormat f = DecimalFormat.getInstance(loc);
if (args.get(0).isNull() || args.get(1).isNull()) {
this.nullValue = true;
return EMPTY;
}
BigDecimal bd = args.get(0).valDecimal();
BigDecimal bdnew = bd.setScale(pl, RoundingMode.HALF_UP);
return f.format(bdnew);
}
项目:hanlpStudy
文件:Evaluator.java
@Override
public String toString()
{
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMinimumFractionDigits(2);
StringBuilder sb = new StringBuilder();
sb.append("UA: ");
sb.append(percentFormat.format(getUA()));
sb.append('\t');
sb.append("LA: ");
sb.append(percentFormat.format(getLA()));
sb.append('\t');
sb.append("DA: ");
sb.append(percentFormat.format(getDA()));
sb.append('\t');
sb.append("sentences: ");
sb.append(sentenceCount);
sb.append('\t');
sb.append("speed: ");
sb.append(sentenceCount / (float)(System.currentTimeMillis() - start) * 1000);
sb.append(" sent/s");
return sb.toString();
}
项目:trashjam2017
文件:GraphEditorWindow.java
/**
* Convert a float to a string format
*
* @param f The float to convert
* @return The string formatted from the float
*/
private String convertFloat(float f) {
NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setMinimumIntegerDigits(1);
format.setMaximumIntegerDigits(5);
return format.format(f);
}
项目:clemon
文件:BackupDatabaseInfo.java
public void setFileSizeSave(long size){
NumberFormat nf=NumberFormat.getNumberInstance() ;
nf.setMaximumFractionDigits(2);
if(size<1024){
fileSize =nf.format(size) +"B";
}else if(size<1024*1024){
this.fileSize =nf.format(size/1024.0) + "KB";
}else if(size<1024*1024*1024){
this.fileSize = nf.format(size/1024.0 * 1024) + "MB";
}else if(size<1024*1024*1024*1024){
this.fileSize = nf.format(size/1024.0 * 1024 * 1024) + "GB";
}
}
项目:aws-sdk-java-v2
文件:S3ListObjectsV2IntegrationTest.java
/**
* Creates all the test resources for the tests.
*/
@BeforeClass
public static void createResources() throws Exception {
createBucket(bucketName);
NumberFormat numberFormatter = new DecimalFormat("##00");
for (int i = 1; i <= BUCKET_OBJECTS; i++) {
createKey("key-" + numberFormatter.format(i));
}
createKey("aaaaa");
createKey("aaaaa/aaaaa");
createKey("aaaaa/aaaaa/aaaaa");
createKey(KEY_NAME_WITH_SPECIAL_CHARS);
}
项目:FinalProject
文件:PostsDetailsActivity.java
private void unLikeMethod() {
sendUnlikeToServer(application, 0, 1, 1, 1, "clicked unlike button");
likeCounter--;
like_counter.setBackgroundColor(getResources().getColor(R.color.white));
like_counter.setTextColor(getResources().getColor(R.color.black));
like_counter.setText("LIKE");
new_counter_like_number.setText(NumberFormat.getIntegerInstance().format(likeCounter));
}
项目:Alpine
文件:ByteFormat.java
/**
* Construct a ByteFormat() instance with the default names[] array and min/max fraction digits.
*
* @since 1.0.0
*/
public ByteFormat() {
numberFormat = NumberFormat.getIntegerInstance();
names = new String[]{" GB", " MB", " KB", " byte"};
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMaximumFractionDigits(1);
}
项目:Keep-HODLing
文件:DashboardFragment.java
void updateValues() {
double effectiveValue = currentPriceDbl * ownedAmountDbl;
NumberFormat formatter = new DecimalFormat("#0.00");
ownedValue.setText(formatter.format(effectiveValue) + " " + preferences.getBaseCurrency());
if (effectiveValue > 0.0 && persistence.getSpentAmount() > 0.0) {
double spent = persistence.getSpentAmount();
double diff = effectiveValue - spent;
double percent = (diff / spent) * 100.0;
if (percent >= 0.01) {
percentValue.setText("▲ " + formatter.format(percent) + " %");
percentValue.setTextColor(getResources().getColor(R.color.money));
} else if (percent <= -0.01) {
percentValue.setText("▼ " + formatter.format(percent) + " %");
percentValue.setTextColor(getResources().getColor(R.color.red));
} else {
percentValue.setText("~ 0.00 %");
percentValue.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
}
} else {
percentValue.setText("~ 0.00 %");
percentValue.setTextColor(getResources().getColor(android.R.color.tab_indicator_text));
}
}
项目:neoscada
文件:LabelProvider.java
private String format ( final Number number )
{
if ( number == null )
{
return Messages.LabelProvider_Text_NA;
}
return NumberFormat.getNumberInstance ().format ( number.doubleValue () );
}
项目:yearyearyear
文件:MessageHandle.java
public static void MessageHandle(TelegramBot tgb, Update msg){
MessageHandle.msg = msg;
MessageHandle.tgb = tgb;
if(msg.getMessage().getFrom().getId() == 123078226){
if(msg.hasMessage()){
if(msg.getMessage().hasText()){
String line = msg.getMessage().getText().replace(" ", "");
Pattern r = Pattern.compile("\\-*[0-9]+\\.[0-9]+,\\-*[0-9]+\\.[0-9]+");
if (r.matcher(line).find()) {
String[] pinfo = line.split(",");
try {
double x,y;
NumberFormat df = NumberFormat.getNumberInstance();
df.setMaximumFractionDigits(6);
x = Float.parseFloat(df.format(Float.parseFloat(pinfo[0])));
y = Float.parseFloat(df.format(Float.parseFloat(pinfo[1])));
findMon(Example.go.get(0),x,y);
}catch(Exception ex){}
}
switch(msg.getMessage().getText().toUpperCase()){
case "IV":
showIV();
break;
case "GAMEID":
showGameId();
break;
}
}
}
}
if(msg.getMessage().hasLocation()){
findMon(Example.go.get(0),msg.getMessage().getLocation().getLatitude(),msg.getMessage().getLocation().getLongitude());
}
}
项目:spring-cloud-dashboard
文件:NumberFormatConverter.java
@Override
public NumberFormat convertFromText(String value, Class<?> targetType, String optionContext) {
if (DEFAULT.equals(value)) {
return NumberFormat.getInstance();
}
else {
return new DecimalFormat(value);
}
}
项目:rapidminer
文件:CSVFileReader.java
public CSVFileReader(final File file, boolean useFirstRowAsColumnNames, LineParser parser, NumberFormat numberFormat) {
this.file = file;
this.useFirstRowAsColumnNames = useFirstRowAsColumnNames;
this.parser = parser;
this.numberFormat = numberFormat;
this.dataEvaluator = new DataEvaluator(numberFormat) {
@Override
public String getGenericColumnName(int column) {
return file.getName() + "_" + (column + 1);
}
};
}
项目:xmrwallet
文件:SendBtcSuccessWizardFragment.java
@Override
public void onResumeFragment() {
super.onResumeFragment();
Timber.d("onResumeFragment()");
Helper.hideKeyboard(getActivity());
isResumed = true;
btcData = (TxDataBtc) sendListener.getTxData();
tvTxAddress.setText(btcData.getDestinationAddress());
String paymentId = btcData.getPaymentId();
if ((paymentId != null) && (!paymentId.isEmpty())) {
tvTxPaymentId.setText(btcData.getPaymentId());
} else {
tvTxPaymentId.setText("-");
}
final PendingTx committedTx = sendListener.getCommittedTx();
if (committedTx != null) {
tvTxId.setText(committedTx.txId);
bCopyTxId.setEnabled(true);
bCopyTxId.setImageResource(R.drawable.ic_content_copy_black_24dp);
tvTxAmount.setText(getString(R.string.send_amount, Helper.getDisplayAmount(committedTx.amount)));
tvTxFee.setText(getString(R.string.send_fee, Helper.getDisplayAmount(committedTx.fee)));
if (btcData != null) {
NumberFormat df = NumberFormat.getInstance(Locale.US);
df.setMaximumFractionDigits(12);
String btcAmount = df.format(btcData.getBtcAmount());
tvXmrToAmount.setText(getString(R.string.info_send_xmrto_success_btc, btcAmount));
//TODO btcData.getBtcAddress();
tvTxXmrToKey.setText(btcData.getXmrtoUuid());
queryOrder();
} else {
throw new IllegalStateException("btcData is null");
}
}
sendListener.enableDone();
}
项目:parabuild-ci
文件:StandardPieItemLabelGenerator.java
/**
* Creates an item label generator using default number formatters.
*/
public StandardPieItemLabelGenerator() {
this(
DEFAULT_SECTION_LABEL_FORMAT,
NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()
);
}
项目:jdk8u-jdk
文件:RoundingAndPropertyTest.java
private static int testLocalizationValues() {
DecimalFormat df = (DecimalFormat)
NumberFormat.getInstance(GoldenDoubleValues.FullLocalizationTestLocale);
double[] localizationValues = GoldenDoubleValues.DecimalLocalizationValues;
int size = localizationValues.length;
int successCounter = 0;
int failureCounter = 0;
for (int i = 0; i < size; i++) {
double d = localizationValues[i];
String formatted = df.format(d);
char[] expectedUnicodeArray =
getCharsFromUnicodeArray(
GoldenFormattedValues.DecimalDigitsLocalizedFormattedValues[i]);
String expected = new String(expectedUnicodeArray);
if (!formatted.equals(expected)) {
failureCounter++;
System.out.println(
"--- Localization error for value d = " + d +
". Exact value = " + new BigDecimal(d).toString() +
". Expected result = " + expected +
". Output result = " + formatted);
} else successCounter++;
}
System.out.println("Checked positively " + successCounter +
" golden decimal values out of " + size +
" tests. There were " + failureCounter +
" format failure");
return failureCounter;
}
项目:myfaces-trinidad
文件:NumberConverter.java
private void _cacheNumberFormat(
NumberFormat format,
String pattern,
String type,
Locale locale)
{
synchronized(_TYPE_LOCK)
{
// -= Simon Lessard =- That if looks paranoid, the map get instanciated
// during static initialization and is never set to
// null
if (_numberFormatHolder == null)
_numberFormatHolder = new HashMap<String, Map<Locale, NumberFormat>>();
else
{
// The key could have either been the type based on which formats are
// stored or it can be based on the pattern also.
String key = ((pattern != null) ? pattern : type);
Map<Locale, NumberFormat> nfMap = _numberFormatHolder.get(key);
// if we have not cached any NumberFormat for this type, then create a
// map for that type and add to it based on the locale
if (nfMap == null)
{
nfMap = new HashMap<Locale, NumberFormat>();
_numberFormatHolder.put(key, nfMap);
}
// add this based on the type ('number','currency','percent') or
// pattern1, pattern2.. patternN to the main holder
nfMap.put(locale, (NumberFormat)format.clone());
}
}
}
项目:parabuild-ci
文件:ThermometerPlot.java
/**
* Sets the formatter for the value label.
*
* @param formatter the new formatter.
*/
public void setValueFormat(NumberFormat formatter) {
if (formatter != null) {
this.valueFormat = formatter;
notifyListeners(new PlotChangeEvent(this));
}
}
项目:GitHub
文件:IntArrayEncodePerformanceTest.java
private void encode(Object object, Codec decoder) throws Exception {
long startNano = System.nanoTime();
for (int i = 0; i < COUNT; ++i) {
decoder.encode(object);
}
long nano = System.nanoTime() - startNano;
System.out.println(decoder.getName() + " : \t" + NumberFormat.getInstance().format(nano));
}
项目:openjdk-jdk10
文件:TestgetPatternSeparator_ja.java
public static void main(String[] argv) throws Exception {
DecimalFormat df = (DecimalFormat)NumberFormat.getInstance(Locale.JAPAN);
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
if (dfs.getPatternSeparator() != ';') {
throw new Exception("DecimalFormatSymbols.getPatternSeparator doesn't return ';' in ja locale");
}
}
项目:NeiHanDuanZiTV
文件:DeviceUtils.java
public static String percent2(double p1, double p2) {
String str;
double p3 = p1 / p2;
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(0);
str = nf.format(p3);
return str;
}
项目:Never-Enough-Currency
文件:CurrencyUtils.java
public static String getAllCurrencyNoWallet(EntityPlayer player) {
float currencyTotal = 0;
for (int i = 0; i < player.inventory.getSizeInventory(); i++) {
if (player.inventory.getStackInSlot(i) != ItemStack.EMPTY && player.inventory.getStackInSlot(i).getItem() instanceof ItemMoneyBase) {
ItemMoneyBase money = (ItemMoneyBase) player.inventory.getStackInSlot(i).getItem();
currencyTotal += (money.getValue() * player.inventory.getStackInSlot(i).getCount());
}
}
NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
return fmt.format(currencyTotal);
}
项目:GitHub
文件:Bug_0_Test.java
private void f_jackson() throws Exception {
long startNano = System.nanoTime();
for (int i = 0; i < COUNT; ++i) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode node = (ArrayNode) mapper.readTree(text);
JsonNode head = node.get(0);
JsonNode body = node.get(1);
}
long nano = System.nanoTime() - startNano;
System.out.println(NumberFormat.getInstance().format(nano));
}
项目:jdk8u-jdk
文件:TieRoundingTest.java
static void formatOutputTestLong(NumberFormat nf,
long longToTest,
String tiePosition,
String inputDigits,
String expectedOutput) {
int mfd = nf.getMaximumFractionDigits();
RoundingMode rm = nf.getRoundingMode();
String result = nf.format(longToTest);
if (!result.equals(expectedOutput)) {
System.out.println();
System.out.println("========================================");
System.out.println("***Failure : error formatting value from string : " +
inputDigits);
System.out.println("NumberFormat pattern is : " +
((DecimalFormat ) nf).toPattern());
System.out.println("Maximum number of fractional digits : " + mfd);
System.out.println("Fractional rounding digit : " + (mfd + 1));
System.out.println("Position of value relative to tie : " + tiePosition);
System.out.println("Rounding Mode : " + rm);
System.out.println(
"Error. Formatted result different from expected." +
"\nExpected output is : \"" + expectedOutput + "\"" +
"\nFormated output is : \"" + result + "\"");
System.out.println("========================================");
System.out.println();
errorCounter++;
allPassed = false;
} else {
testCounter++;
System.out.print("Success. Long input :" + inputDigits);
System.out.print(", rounding : " + rm);
System.out.print(", fract digits : " + mfd);
System.out.print(", tie position : " + tiePosition);
System.out.println(", expected : " + expectedOutput);
}
}
项目:GitHub
文件:RxFileDownloadActivity.java
@Override
protected void onActivityCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_rx_file_download);
ButterKnife.bind(this);
setTitle("文件下载");
numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(2);
checkSDCardPermission();
}
项目:applecommander
文件:DosFileEntry.java
/**
* Get the standard file column header information.
* This default implementation is intended only for standard mode.
* displayMode is specified in FormattedDisk.
*/
public List getFileColumnData(int displayMode) {
NumberFormat numberFormat = NumberFormat.getNumberInstance();
List list = new ArrayList();
switch (displayMode) {
case FormattedDisk.FILE_DISPLAY_NATIVE:
list.add(isLocked() ? "*" : " "); //$NON-NLS-1$ //$NON-NLS-2$
list.add(getFiletype());
numberFormat.setMinimumIntegerDigits(3);
list.add(numberFormat.format(getSectorsUsed()));
list.add(getFilename());
break;
case FormattedDisk.FILE_DISPLAY_DETAIL:
list.add(isLocked() ? "*" : " "); //$NON-NLS-1$ //$NON-NLS-2$
list.add(getFiletype());
list.add(getFilename());
list.add(numberFormat.format(getSize()));
numberFormat.setMinimumIntegerDigits(3);
list.add(numberFormat.format(getSectorsUsed()));
list.add(isDeleted() ? textBundle.get("Deleted") : ""); //$NON-NLS-1$//$NON-NLS-2$
list.add("T" + getTrack() + " S" + getSector()); //$NON-NLS-1$ //$NON-NLS-2$
break;
default: // FILE_DISPLAY_STANDARD
list.add(getFilename());
list.add(getFiletype());
list.add(numberFormat.format(getSize()));
list.add(isLocked() ? textBundle.get("Locked") : ""); //$NON-NLS-1$//$NON-NLS-2$
break;
}
return list;
}