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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}