Java Code Examples for java.text.NumberFormat

The following are top voted examples for showing how to use java.text.NumberFormat. 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: lams   File: NumberUtil.java   Source Code and License 6 votes vote down vote up
/**
    * 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());
   }
 
Example 2
Project: openjdk-jdk10   File: Bug6278616.java   Source Code and License 6 votes vote down vote up
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 + ")");
        }
    }
}
 
Example 3
Project: DateTimePicker   File: SimpleMonthView.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 4
Project: AgentWorkbench   File: SystemLoadPanel.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Project: geomapapp   File: GeneralUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: VanillaPlus   File: Currency.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 7
Project: parabuild-ci   File: MeterPlot.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 8
Project: HackerRank-Studies   File: Solution.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 9
Project: jdk8u-jdk   File: FormatMicroBenchmark.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 10
Project: OpenDA   File: ASCIIVectorIoObject.java   Source Code and License 6 votes vote down vote up
@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();
	}
}
 
Example 11
Project: ACE_HackerRank   File: Solution.java   Source Code and License 6 votes vote down vote up
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));
}
 
Example 12
Project: swage   File: DoubleFormatTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 13
Project: aliyun-maxcompute-data-collectors   File: PerfCounters.java   Source Code and License 6 votes vote down vote up
/**
 * @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;
}
 
Example 14
Project: baud   File: BaudEntryDay.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 15
Project: incubator-netbeans   File: LockCCTNode.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 16
Project: dble   File: ItemFuncFormat.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 17
Project: hanlpStudy   File: Evaluator.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 18
Project: trashjam2017   File: GraphEditorWindow.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 19
Project: clemon   File: BackupDatabaseInfo.java   Source Code and License 5 votes vote down vote up
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";
	}	
}
 
Example 20
Project: aws-sdk-java-v2   File: S3ListObjectsV2IntegrationTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 21
Project: FinalProject   File: PostsDetailsActivity.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 22
Project: Alpine   File: ByteFormat.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 23
Project: Keep-HODLing   File: DashboardFragment.java   Source Code and License 5 votes vote down vote up
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));
    }
}
 
Example 24
Project: neoscada   File: LabelProvider.java   Source Code and License 5 votes vote down vote up
private String format ( final Number number )
{
    if ( number == null )
    {
        return Messages.LabelProvider_Text_NA;
    }
    return NumberFormat.getNumberInstance ().format ( number.doubleValue () );
}
 
Example 25
Project: yearyearyear   File: MessageHandle.java   Source Code and License 5 votes vote down vote up
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());
	}
}
 
Example 26
Project: spring-cloud-dashboard   File: NumberFormatConverter.java   Source Code and License 5 votes vote down vote up
@Override
public NumberFormat convertFromText(String value, Class<?> targetType, String optionContext) {
	if (DEFAULT.equals(value)) {
		return NumberFormat.getInstance();
	}
	else {
		return new DecimalFormat(value);
	}
}
 
Example 27
Project: rapidminer   File: CSVFileReader.java   Source Code and License 5 votes vote down vote up
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);
		}
	};
}
 
Example 28
Project: xmrwallet   File: SendBtcSuccessWizardFragment.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 29
Project: parabuild-ci   File: StandardPieItemLabelGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an item label generator using default number formatters.
 */
public StandardPieItemLabelGenerator() {
    this(
        DEFAULT_SECTION_LABEL_FORMAT, 
        NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()
    );
}
 
Example 30
Project: jdk8u-jdk   File: RoundingAndPropertyTest.java   Source Code and License 5 votes vote down vote up
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;
    }
 
Example 31
Project: myfaces-trinidad   File: NumberConverter.java   Source Code and License 5 votes vote down vote up
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());
    }
  }
}
 
Example 32
Project: parabuild-ci   File: ThermometerPlot.java   Source Code and License 5 votes vote down vote up
/**
 * 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));
  }
}
 
Example 33
Project: GitHub   File: IntArrayEncodePerformanceTest.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 34
Project: openjdk-jdk10   File: TestgetPatternSeparator_ja.java   Source Code and License 5 votes vote down vote up
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");
    }
}
 
Example 35
Project: NeiHanDuanZiTV   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: Never-Enough-Currency   File: CurrencyUtils.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: GitHub   File: Bug_0_Test.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 38
Project: jdk8u-jdk   File: TieRoundingTest.java   Source Code and License 5 votes vote down vote up
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);

    }
}
 
Example 39
Project: GitHub   File: RxFileDownloadActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onActivityCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_rx_file_download);
    ButterKnife.bind(this);
    setTitle("文件下载");

    numberFormat = NumberFormat.getPercentInstance();
    numberFormat.setMinimumFractionDigits(2);

    checkSDCardPermission();
}
 
Example 40
Project: applecommander   File: DosFileEntry.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 41
Project: GitHub   File: DesActivity.java   Source Code and License 5 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_details);
        initToolBar(toolbar, true, "下载管理");

        apk = (ApkModel) getIntent().getSerializableExtra("apk");
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);

        // 写法一:从内存中获取
        if (OkDownload.getInstance().hasTask(apk.url)) {
            task = OkDownload.getInstance().getTask(apk.url)//
                    .register(new DesListener("DesListener"))//
                    .register(new LogDownloadListener());
        }

        //写法二:从数据库中恢复
//        Progress progress = DownloadManager.getInstance().get(apk.getUrl());
//        if (progress != null) {
//            task = OkDownload.restore(progress)//
//                    .register(new DesListener("DesListener"))//
//                    .register(new LogDownloadListener());
//        }

        displayImage(apk.iconUrl, icon);
        name.setText(apk.name);
        if (task != null) refreshUi(task.progress);
    }
 
Example 42
Project: DiscogsBrowser   File: OrderReleaseModel.java   Source Code and License 5 votes vote down vote up
@Override
public void bind(LinearLayout view)
{
    ButterKnife.bind(this, view);
    NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
    tvPrice.setText(numberFormat.format(price));
    tvReleaseName.setText(releaseName);
}
 
Example 43
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 44
Project: jaer   File: FilterPanel.java   Source Code and License 5 votes vote down vote up
void fixIntValue(JTextField tf, Method r) {
        // set text to actual value
        try {
            Integer x = (Integer) r.invoke(getFilter()); // read int value
//            initValue=x.intValue();
            String s = NumberFormat.getIntegerInstance().format(x);
            tf.setText(s);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }
 
Example 45
Project: hadoop   File: JobId.java   Source Code and License 5 votes vote down vote up
@Override
public NumberFormat initialValue() {
  NumberFormat fmt = NumberFormat.getInstance();
  fmt.setGroupingUsed(false);
  fmt.setMinimumIntegerDigits(4);
  return fmt;
}
 
Example 46
Project: incubator-netbeans   File: HintsController.java   Source Code and License 5 votes vote down vote up
private String findBiggestObjects(int number) {
    Heap heap = getSummaryController().getHeapFragmentWalker().getHeapFragment();
    List<Instance> bigObjects = heap.getBiggestObjectsByRetainedSize(number);
    StringBuffer output = new StringBuffer();
    JavaClass java_lang_Class = heap.getJavaClassByName(Class.class.getName());
    NumberFormat formatter =  NumberFormat.getInstance();
    boolean oddRow = false;
    Color oddRowBackground = UIUtils.getDarker(
                    UIUtils.getProfilerResultsBackground());
    final String oddRowBackgroundString =
            "rgb(" + oddRowBackground.getRed() + "," + //NOI18N
                     oddRowBackground.getGreen() + "," + //NOI18N
                     oddRowBackground.getBlue() + ")"; //NOI18N
    
    output.append("<table border='0' width='100%'>");  // NOI18N
    output.append("<tr style='background-color:");  // NOI18N
    output.append(oddRowBackgroundString).append(";'>");  // NOI18N
    addHeading(output, Bundle.HintsController_ClassName());
    addHeading(output, Bundle.HintsController_RetainedSize());
    output.append("</tr>"); // NOI18N
    for(Instance in : bigObjects) {
        output.append(oddRow ? "<tr style='background-color: " + // NOI18N
                                  oddRowBackgroundString + ";'>" :  // NOI18N
                                  "<tr>");  // NOI18N
        if (in.getJavaClass().equals(java_lang_Class)) {
            JavaClass javaClass = heap.getJavaClassByID(in.getInstanceId());
            addCell(output,printClass(javaClass), false);
        } else {
            addCell(output,printInstance(in), false);
        }
        addCell(output,formatter.format(in.getRetainedSize()), true);
        output.append("</tr>");   // NOI18N
        oddRow = !oddRow;
    }
    output.append("</table>");   // NOI18N
    return output.toString();
}
 
Example 47
Project: financisto1-holo   File: Currency.java   Source Code and License 5 votes vote down vote up
public NumberFormat getFormat() {
	DecimalFormat f = format;
	if (f == null) {
		f = CurrencyCache.createCurrencyFormat(this);
		format = f;
	}
	return f;
}
 
Example 48
Project: mumu   File: DiliverPerUtil.java   Source Code and License 5 votes vote down vote up
public static String setDiliverPer(int diliverNum, int queryMailNum) {
	NumberFormat numberFormat = NumberFormat.getInstance();
	// 设置精确到小数点后2位
	numberFormat.setMaximumFractionDigits(2);
	String result = numberFormat.format((float) diliverNum / (float) queryMailNum * 100);
	return result;
}
 
Example 49
Project: openNaEF   File: DistributedTransactionService.java   Source Code and License 5 votes vote down vote up
Impl(int port, String serviceName, String[] acceptableTefServiceIds)
        throws RemoteException, AlreadyBoundException {
    synchronized (Impl.class) {
        if (instance__ != null) {
            throw new IllegalStateException();
        } else {
            instance__ = this;
        }
    }

    Logs logs = new Logs(System.currentTimeMillis(), new File("."), "logs");
    transactionCoordinationLogger_ = logs.createLogger("distributed-transactions");

    tefServices_ = new HashMap<String, TefServiceProxy>();
    for (String acceptableTefServiceId : acceptableTefServiceIds) {
        tefServices_.put(acceptableTefServiceId, null);
    }

    tefServiceIndexes_ = new HashMap<String, Integer>();
    for (int i = 0; i < acceptableTefServiceIds.length; i++) {
        tefServiceIndexes_.put(acceptableTefServiceIds[i], new Integer(i));
    }

    try {
        history_
                = restoreTxHistory(transactionCoordinationLogger_.getFile().getParentFile());
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    System.out.println("restored: " + history_.size());
    System.gc();
    long memoryUsage
            = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.out.println("memory: " + NumberFormat.getInstance().format(memoryUsage));

    Registry registry = LocateRegistry.createRegistry(port);
    registry.bind(serviceName, this);
}
 
Example 50
Project: iBase4J   File: TypeParseUtil.java   Source Code and License 5 votes vote down vote up
private static NumberFormat getNf(Locale locale) {
	NumberFormat nf = null;
	if (locale == null) {
		nf = NumberFormat.getNumberInstance();
	} else {
		nf = NumberFormat.getNumberInstance(locale);
	}
	nf.setGroupingUsed(false);
	return nf;
}
 
Example 51
Project: PicShow-zhaipin   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
public static String percent(double p1, double p2) {
    String str;
    double p3 = p1 / p2;
    NumberFormat nf = NumberFormat.getPercentInstance();
    nf.setMinimumFractionDigits(2);
    str = nf.format(p3);
    return str;
}
 
Example 52
Project: geomapapp   File: ProjectionDialog.java   Source Code and License 5 votes vote down vote up
void setProjection() {
	// Add formatter to restrict size of WESN strings for display
	NumberFormat fmtWESN = NumberFormat.getInstance();
	fmtWESN.setMaximumFractionDigits(3);
	fmtWESN.setMinimumFractionDigits(3);

	if( type.getSelectedIndex() == GEOGRAPHIC_PROJECTION ) {
		zone.setEnabled(false);
		if( wesn!=null ) {
			// Format WESN strings
			wesnLabel.setText(fmtWESN.format(wesn[0]) + ",\t      " +	// W
							fmtWESN.format(wesn[1]) + ",\t     " +		// E
							fmtWESN.format(wesn[2]) + ",\t     " +		// S
							fmtWESN.format(wesn[3]) );					// N
		}
		if(wesnRangeAllGrids!=null) {
			allWESNLabel.setText(fmtWESN.format(wesnRangeAllGrids[0]) + ",\t      " +	// W
					fmtWESN.format(wesnRangeAllGrids[1]) + ",\t     " +					// E
					fmtWESN.format(wesnRangeAllGrids[2]) + ",\t     " +					// S
					fmtWESN.format(wesnRangeAllGrids[3]) );								// N
		}
	} else if (type.getSelectedIndex() == UTM_PROJECTION) {
		zone.setEnabled(true);
		if( wesn!=null ) {
			wesnLabel.setText(fmtWESN.format(wesn[0]) + ",\t      " +	// W
					fmtWESN.format(wesn[1]) + ",\t     " +				// E
					fmtWESN.format(wesn[2]) + ",\t     " +				// S
					fmtWESN.format(wesn[3]) + " ");						// N
		}
		if(wesnRangeAllGrids!=null) {
			allWESNLabel.setText(fmtWESN.format(wesnRangeAllGrids[0]) + ",\t      " +	// W
					fmtWESN.format(wesnRangeAllGrids[1]) + ",\t     " +					// E
					fmtWESN.format(wesnRangeAllGrids[2]) + ",\t     " +					// S
					fmtWESN.format(wesnRangeAllGrids[3]) );								// N
		}
		
	}
}
 
Example 53
Project: dacapobench   File: FullSourceWorkspaceCompleteSearchTests.java   Source Code and License 5 votes vote down vote up
public void testSearchStringConstructorReferences() throws CoreException {

    // Wait for indexing end
    waitUntilIndexesReady();

    // Warm up
    String name = "()";
    JavaSearchResultCollector resultCollector = new JavaSearchResultCollector();
    search(name, CONSTRUCTOR, REFERENCES, resultCollector);
    NumberFormat intFormat = NumberFormat.getIntegerInstance();
    if (DACAPO_PRINT)
      System.out.print(" " + intFormat.format(resultCollector.count) + " references for default constructor in workspace");
  }
 
Example 54
Project: bean-grid   File: StringToBigIntegerBeanConverter.java   Source Code and License 5 votes vote down vote up
@Override
protected NumberFormat getFormat(ValueContext context) {
	NumberFormat format = super.getFormat(context);

	if (format instanceof DecimalFormat) {
		((DecimalFormat) format).setParseBigDecimal(true);
	}

	return format;
}
 
Example 55
Project: cleaninsights-android-sdk   File: CurrencyFormatter.java   Source Code and License 5 votes vote down vote up
@Nullable
public static String priceString(@Nullable Integer cents) {
    if (cents == null) return null;
    NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(cents / 100.);
}
 
Example 56
Project: OpenJSharp   File: SPILocaleProviderAdapter.java   Source Code and License 4 votes vote down vote up
@Override
public NumberFormat getCurrencyInstance(Locale locale) {
    NumberFormatProvider nfp = getImpl(locale);
    assert nfp != null;
    return nfp.getCurrencyInstance(locale);
}
 
Example 57
Project: OpenJSharp   File: SPILocaleProviderAdapter.java   Source Code and License 4 votes vote down vote up
@Override
public NumberFormat getPercentInstance(Locale locale) {
    NumberFormatProvider nfp = getImpl(locale);
    assert nfp != null;
    return nfp.getPercentInstance(locale);
}
 
Example 58
Project: holon-vaadin7   File: NumberField.java   Source Code and License 4 votes vote down vote up
/**
 * Sets a fixed NumberFormat to use for value conversions from user input field and back.
 * @param numberFormat the NumberFormat to set
 */
public void setNumberFormat(NumberFormat numberFormat) {
	StringToNumberConverter<T> converter = new StringToNumberConverter<>(getType());
	converter.setNumberFormat(numberFormat);
	getInternalField().setConverter(converter);
}
 
Example 59
Project: Google-Developer-Challenge-Scholarship-Android-Basics   File: MainActivity.java   Source Code and License 4 votes vote down vote up
/**
 * This method displays the given price on the screen.
 */
private void displayPrice(int number) {
    TextView priceTextView = findViewById(R.id.price_text_view);
    priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
 
Example 60
Project: Library-System-Android   File: Confirm.java   Source Code and License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.confirm);

    //Reservations counter
    ArrayList<Transaction> transactions = new ArrayList<>(db.getAllTransactions());
    for(Transaction transaction : transactions){
        if(transaction.getTypeNumber()==1){reservation++;}
    }

    View test = findViewById(R.id.confirm_button);
    test.setOnClickListener(this);

    TextView main = (TextView) findViewById(R.id.main);

    //***GET PASSED INFO***
    Bundle extras= getIntent().getExtras();
    //PickUp
    String pickUpYear = extras.getString("pickUpYear");
    String pickUpMonth = extras.getString("pickUpMonth");
    String pickUpDay = extras.getString("pickUpDay");
    String pickUpHour = extras.getString("pickUpHour");
    String pickUpAmPm = extras.getString("pickUpAmPm");
    //DropOff
    String dropOffYear = extras.getString("dropOffYear");
    String dropOffMonth = extras.getString("dropOffMonth");
    String dropOffDay = extras.getString("dropOffDay");
    String dropOffHour = extras.getString("dropOffHour");
    String dropOffAmPm = extras.getString("dropOffAmPm");
    //Transaction
    String loggedUsername = extras.getString("username");
    String bookTitle = extras.getString("title");
    double rentalTotal = extras.getDouble("rentalTotal");

    //Transaction Date and time for Pickup
    String pickUpDateTime;
    pickUpDateTime = getMonthNumber(pickUpMonth) +"/" + pickUpDay + "/" + pickUpYear+ " (" + pickUpHour +" "+ pickUpAmPm + ")";
    //Transaction Date and time for Dropoff
    String dropOffDateTime;
    dropOffDateTime = getMonthNumber(dropOffMonth) +"/" + dropOffDay + "/" + dropOffYear + " (" + dropOffHour +" "+ dropOffAmPm + ")";


    //Add info for rental into details box
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    main.setText("");
    main.append("Username: " + loggedUsername + " \n");
    main.append("Pick Up/Date Time: " + pickUpDateTime + " \n");
    main.append("Return/Date Time: " + dropOffDateTime + " \n");
    main.append("Book Title: " + bookTitle + " \n");
    main.append("Reservation Number: " + (reservation+1) + " \n");
    main.append("Total Rental Cost: " + formatter.format(rentalTotal) + " \n");
}