java.text.NumberFormat#getCurrencyInstance ( )源码实例Demo

下面列出了java.text.NumberFormat#getCurrencyInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: j2objc   文件: NumberFormatTest.java
public void test_issue79925() {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
    nf.setCurrency(Currency.getInstance("EUR"));
    assertEquals("€50.00", nf.format(50.0));

    DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
    decimalFormatSymbols.setCurrencySymbol("");
    ((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
    assertEquals("50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.00));

    nf.setCurrency(Currency.getInstance("USD"));
    assertEquals("$50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.0));
}
 
源代码2 项目: openjdk-8   文件: Bug4651568.java
public static void main (String argv[] )  {
    Locale reservedLocale = Locale.getDefault();
    try {
        String expectedCurrencyPattern = "\u00A4 #.##0,00";

        Locale locale = new Locale ("pt", "BR");
        Locale.setDefault(locale);

        DecimalFormat formatter =
            (DecimalFormat) NumberFormat.getCurrencyInstance(locale);

        if (formatter.toLocalizedPattern().equals(
                    expectedCurrencyPattern)) {
            System.out.println ("Passed.");
        } else {
             System.out.println ("Failed Currency pattern." +
                    "  Expected:  " + expectedCurrencyPattern +
                    "  Received:  " + formatter.toLocalizedPattern() );
             throw new RuntimeException();

        }
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
源代码3 项目: jdk8u60   文件: Bug4651568.java
public static void main (String argv[] )  {
    Locale reservedLocale = Locale.getDefault();
    try {
        String expectedCurrencyPattern = "\u00A4 #.##0,00";

        Locale locale = new Locale ("pt", "BR");
        Locale.setDefault(locale);

        DecimalFormat formatter =
            (DecimalFormat) NumberFormat.getCurrencyInstance(locale);

        if (formatter.toLocalizedPattern().equals(
                    expectedCurrencyPattern)) {
            System.out.println ("Passed.");
        } else {
             System.out.println ("Failed Currency pattern." +
                    "  Expected:  " + expectedCurrencyPattern +
                    "  Received:  " + formatter.toLocalizedPattern() );
             throw new RuntimeException();

        }
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
@Override
protected NumberFormat getNumberFormat(Locale locale) {
	DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
	format.setParseBigDecimal(true);
	format.setMaximumFractionDigits(this.fractionDigits);
	format.setMinimumFractionDigits(this.fractionDigits);
	if (this.roundingMode != null) {
		format.setRoundingMode(this.roundingMode);
	}
	if (this.currency != null) {
		format.setCurrency(this.currency);
	}
	if (this.pattern != null) {
		format.applyPattern(this.pattern);
	}
	return format;
}
 
源代码5 项目: jdk8u-dev-jdk   文件: Bug4651568.java
public static void main (String argv[] )  {
    Locale reservedLocale = Locale.getDefault();
    try {
        String expectedCurrencyPattern = "\u00A4 #.##0,00";

        Locale locale = new Locale ("pt", "BR");
        Locale.setDefault(locale);

        DecimalFormat formatter =
            (DecimalFormat) NumberFormat.getCurrencyInstance(locale);

        if (formatter.toLocalizedPattern().equals(
                    expectedCurrencyPattern)) {
            System.out.println ("Passed.");
        } else {
             System.out.println ("Failed Currency pattern." +
                    "  Expected:  " + expectedCurrencyPattern +
                    "  Received:  " + formatter.toLocalizedPattern() );
             throw new RuntimeException();

        }
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
源代码6 项目: hottub   文件: Bug4651568.java
public static void main (String argv[] )  {
    Locale reservedLocale = Locale.getDefault();
    try {
        String expectedCurrencyPattern = "\u00A4 #.##0,00";

        Locale locale = new Locale ("pt", "BR");
        Locale.setDefault(locale);

        DecimalFormat formatter =
            (DecimalFormat) NumberFormat.getCurrencyInstance(locale);

        if (formatter.toLocalizedPattern().equals(
                    expectedCurrencyPattern)) {
            System.out.println ("Passed.");
        } else {
             System.out.println ("Failed Currency pattern." +
                    "  Expected:  " + expectedCurrencyPattern +
                    "  Received:  " + formatter.toLocalizedPattern() );
             throw new RuntimeException();

        }
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
源代码7 项目: lams   文件: CurrencyStyleFormatter.java
@Override
protected NumberFormat getNumberFormat(Locale locale) {
	DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
	format.setParseBigDecimal(true);
	format.setMaximumFractionDigits(this.fractionDigits);
	format.setMinimumFractionDigits(this.fractionDigits);
	if (this.roundingMode != null) {
		format.setRoundingMode(this.roundingMode);
	}
	if (this.currency != null) {
		format.setCurrency(this.currency);
	}
	if (this.pattern != null) {
		format.applyPattern(this.pattern);
	}
	return format;
}
 
源代码8 项目: jdk8u-jdk   文件: Bug4651568.java
public static void main (String argv[] )  {
    Locale reservedLocale = Locale.getDefault();
    try {
        String expectedCurrencyPattern = "\u00A4 #.##0,00";

        Locale locale = new Locale ("pt", "BR");
        Locale.setDefault(locale);

        DecimalFormat formatter =
            (DecimalFormat) NumberFormat.getCurrencyInstance(locale);

        if (formatter.toLocalizedPattern().equals(
                    expectedCurrencyPattern)) {
            System.out.println ("Passed.");
        } else {
             System.out.println ("Failed Currency pattern." +
                    "  Expected:  " + expectedCurrencyPattern +
                    "  Received:  " + formatter.toLocalizedPattern() );
             throw new RuntimeException();

        }
    } finally {
        // restore the reserved locale
        Locale.setDefault(reservedLocale);
    }
}
 
源代码9 项目: FormattEditText   文件: CurrencyEditText.java
/**
 * Returns decimal formatter for specified currency.
 *
 * @return Currency formatter for current locale and currency.
 */
private DecimalFormat getCurrencyFormatter() {
	NumberFormat.getCurrencyInstance();
	NumberFormat format = NumberFormat.getCurrencyInstance(locale);
	format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
	format.setCurrency(currency);
	return (DecimalFormat) format;
}
 
源代码10 项目: j2objc   文件: MessageFormatTest.java
public void test_setFormats$Ljava_text_Format() throws Exception {
  MessageFormat f1 = (MessageFormat) format1.clone();

  // case 1: Test with repeating formats and max argument index < max
  // offset
  // compare getFormats() results after calls to setFormats(Format[])
  Format[] correctFormats = new Format[] {
    DateFormat.getTimeInstance(),
    new ChoiceFormat("0#off|1#on"),
    DateFormat.getTimeInstance(),
    NumberFormat.getCurrencyInstance(),
    new ChoiceFormat("1#few|2#ok|3#a lot")
  };

  f1.setFormats(correctFormats);
  Format[] formats = f1.getFormats();

  assertTrue("Test1A:Returned wrong number of formats:", correctFormats.length <= formats.length);
  for (int i = 0; i < correctFormats.length; i++) {
    assertEquals("Test1B:wrong format for argument index " + i + ":", correctFormats[i], formats[i]);
  }

  // case 2: Try to pass null argument to setFormats().
  try {
    f1.setFormats(null);
    fail();
  } catch (NullPointerException expected) {
  }
}
 
源代码11 项目: FoodOrdering   文件: Activity_Payment.java
private void initView() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("");
    TextView toolbarText = (TextView) findViewById(R.id.toolbar_text);
    toolbarText.setText("支付订单");
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    nf = NumberFormat.getCurrencyInstance();
    nf.setMaximumFractionDigits(2);
    recyclerView_payment = (RecyclerView) findViewById(R.id.recycler_payment);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView_payment.setLayoutManager(layoutManager);
    Adapter_PaymentWay adapter = new Adapter_PaymentWay(getPayWayData());
    recyclerView_payment.setAdapter(adapter);

    confirm_pay = (Button) findViewById(R.id.confirm_pay);
    tv_remaining_time = (TextView) findViewById(R.id.tv_remaining_time);
    tv_cost = (TextView) findViewById(R.id.tv_cost);
    business_nameAndId = (TextView) findViewById(R.id.business_nameAndId);

    confirm_pay.setOnClickListener(this);
    tv_cost.setText(nf.format(cost));
    if (businessList != null) {
        business_nameAndId.setText(businessList.get(0).getName() + "-" + businessList.get(0).getId());
    }
    confirm_pay.setText("确认支付" + nf.format(cost));
}
 
源代码12 项目: TencentKona-8   文件: TestPeruCurrencyFormat.java
public static void main(String[] args) {
    final String expected = "S/.1,234.56";
    NumberFormat currencyFmt =
            NumberFormat.getCurrencyInstance(new Locale("es", "PE"));
    String s = currencyFmt.format(1234.56);

    if (!s.equals(expected)) {
        throw new RuntimeException("Currency format for Peru failed, expected " + expected + ", got " + s);
    }
}
 
源代码13 项目: jdk8u_jdk   文件: RoundingAndPropertyTest.java
public static void main(String[] args) {

        if ((args.length >= 1) &&
            (args[0].equals("-gengold")))
            generatesGoldenFormattedValuesClass();
        else {
            System.out.println("\nChecking correctness of formatting with digit localization.");
            System.out.println("=============================================================");
            int localizationErrors = testLocalizationValues();
            if (localizationErrors != 0)
                System.out.println("*** Failure in localization tests : " +
                                   localizationErrors + " errors detected ");
            else System.out.println(" Tests for full localization of digits all passed.");

            DecimalFormat df = (DecimalFormat)
                NumberFormat.getInstance(GoldenDoubleValues.TestLocale);
            DecimalFormat cf = (DecimalFormat)
                NumberFormat.getCurrencyInstance(GoldenDoubleValues.TestLocale);

            System.out.println("\nChecking correctness of formating for golden values.");
            System.out.println("=============================================================");
            int goldenValuesErrors = testGoldenValues(df,cf);
            if (goldenValuesErrors != 0)
                System.out.println("*** Failure in goldenValues tests : " +
                                   goldenValuesErrors + " errors detected ");
            else System.out.println(" Tests for golden values all passed.");

            System.out.println("\nChecking behavior of property changes for decimal case.");
            System.out.println("=============================================================");
            int decimalTestsErrors = testSettersAndFastPath(df, false);
            if (decimalTestsErrors != 0)
                System.out.println("*** Failure in decimal property changes tests : " +
                                   decimalTestsErrors + " errors detected ");
            else System.out.println(" Tests for decimal property changes all passed.");

            System.out.println("\nChecking behavior of property changes for currency case.");
            System.out.println("=============================================================");
            int currencyTestsErrors = testSettersAndFastPath(cf, true);
            if (currencyTestsErrors != 0)
                System.out.println("*** Failure in currency property changes tests : " +
                                   currencyTestsErrors + " errors detected ");
            else System.out.println(" Tests for currency property chamges all passed.");

            if ((localizationErrors > 0) ||
                (goldenValuesErrors > 0) ||
                (decimalTestsErrors > 0) ||
                (currencyTestsErrors > 0))
                throw new RuntimeException(
                    "Failed with " +
                    (localizationErrors + goldenValuesErrors +
                     decimalTestsErrors + currencyTestsErrors) +
                    " error(s).");
        }
    }
 
源代码14 项目: hottub   文件: Test6462562.java
void testCurrencyFormat() {
    NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
    TestFormattedTextField ftf = create(format);
    ftf.setValue(56L);

    System.err.println("Testing NumberFormat.getCurrencyInstance(Locale.US)");

    // test inserting individual characters
    ftf.test(1, 0, "1", 16L);
    ftf.test(3, 0, "2", 162L);
    ftf.test(2, 0, "0", 102L);

    // test inserting several characters at once - e.g. from clipboard
    ftf.test(1, 0, "1024", 1024L);
    ftf.test(4, 0, "333", 10333L);
    ftf.test(7, 0, "77", 1033377L);
    ftf.test(5, 0, "99", 1039977L);
    ftf.test(7, 0, "00", 1039007L);

    // test inserting strings that contain some formatting
    ftf.test(1, 0, "2,2", 229007L);
    ftf.test(3, 0, "2,2", 22227L);
    ftf.test(4, 0, "2,2", 2222L);
    ftf.test(6, 0, "33,33", 22223333L);

    // test delete
    ftf.test(1, 0, DELETE, 2223333L);
    ftf.test(10, 0, DELETE, 2223333L);
    ftf.test(5, 0, DELETE, 222333L);
    ftf.test(5, 0, DELETE, 22233L);

    // test backspace
    ftf.test(1, 0, BACKSPACE, 22233L);
    ftf.test(7, 0, BACKSPACE, 2223L);
    ftf.test(4, 0, BACKSPACE, 223L);
    ftf.test(2, 0, BACKSPACE, 23L);

    // test replacing selection
    ftf.test(1, 1, "555", 5553L);
    ftf.test(4, 2, "555", 55555L);
    ftf.test(2, 3, "1", 5155L);
    ftf.test(3, 2, "6", 565L);
    ftf.test(1, 3, "111222333444555", 111222333444555L);

    // test deleting selection
    ftf.test(1, 2, DELETE, 1222333444555L);
    ftf.test(1, 3, BACKSPACE, 22333444555L);
    ftf.test(13, 2, DELETE, 223334445L);
    ftf.test(10, 2, BACKSPACE, 2233344L);
    ftf.test(4, 4, DELETE, 2244L);
    ftf.test(1, 4, BACKSPACE, 4L);
}
 
源代码15 项目: mobikul-standalone-pos   文件: Helper.java
public static String currencyFormater(double rate, Context context) {
    Locale us = new Locale("en", AppSharedPref.getSelectedCurrency(context).substring(0, 2));
    NumberFormat usFormat = NumberFormat.getCurrencyInstance(us);
    return usFormat.format(rate);
}
 
/**
 * Handle switching to local currency
 */
private void switchCurrency() {
    // Keep a cache of previous amounts because, it's kinda nice to see approx what nano is worth
    // this way you can tap button and tap back and not end up with X.9993451 NANO
    if (useLocalCurrency) {
        // Switch back to NANO
        binding.sendAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        if (lastLocalCurrencyAmount != null && lastNanoAmount != null && wallet.getLocalCurrencyAmountNoSymbol().equals(lastLocalCurrencyAmount)) {
            lastLocalCurrencyAmount = wallet.getLocalCurrencyAmountNoSymbol();
            wallet.setSendNanoAmount(lastNanoAmount);
        } else {
            lastLocalCurrencyAmount = wallet.getLocalCurrencyAmountNoSymbol();
        }
        useLocalCurrency = false;
        binding.sendAmount.setText(wallet.getSendNanoAmountFormatted());
        lastNanoAmount = wallet.getSendNanoAmount();
        binding.sendBalance.setText(getString(R.string.send_balance, wallet.getAccountBalanceBanano()));
        binding.sendAmount.setFilters(new InputFilter[]{new DigitsInputFilter(Integer.MAX_VALUE, 6, Integer.MAX_VALUE)});
    } else {
        // Switch to local currency);
        NumberFormat nf = NumberFormat.getCurrencyInstance(wallet.getLocalCurrency().getLocale());
        String allowedChars = "0123456789.";
        if (nf instanceof DecimalFormat) {
            DecimalFormatSymbols sym = ((DecimalFormat)nf).getDecimalFormatSymbols();
            allowedChars = String.format("0123456789%s", sym.getDecimalSeparator());
        }
        binding.sendAmount.setKeyListener(DigitsKeyListener.getInstance(allowedChars));
        if (lastNanoAmount != null && lastLocalCurrencyAmount != null && wallet.getSendNanoAmount().equals(lastNanoAmount)) {
            lastNanoAmount = wallet.getSendNanoAmount();
            wallet.setLocalCurrencyAmount(lastLocalCurrencyAmount);
        } else {
            lastNanoAmount = wallet.getSendNanoAmount();
        }
        useLocalCurrency = true;
        binding.sendAmount.setText(wallet.getLocalCurrencyAmountNoSymbol());
        lastLocalCurrencyAmount = wallet.getLocalCurrencyAmountNoSymbol();
        binding.sendBalance.setText(String.format("(%s)", wallet.getAccountBalanceLocalCurrency()));
        binding.sendAmount.setFilters(new InputFilter[]{new DigitsInputFilter(Integer.MAX_VALUE, 2, Integer.MAX_VALUE)});
    }
    binding.sendAmount.setSelection(binding.sendAmount.getText().length());
}
 
源代码17 项目: j2objc   文件: DecimalFormatTest.java
private String formatArbitraryCurrencyAmountInLocale(Currency currency, Locale locale) {
    NumberFormat localeCurrencyFormat = NumberFormat.getCurrencyInstance(locale);
    localeCurrencyFormat.setCurrency(currency);
    return localeCurrencyFormat.format(1000);
}
 
源代码18 项目: mobikul-standalone-pos   文件: Helper.java
public static String currencyFormater(double rate, String code) {
    Locale us = new Locale("en", code.substring(0, 2));
    NumberFormat usFormat = NumberFormat.getCurrencyInstance(us);
    return usFormat.format(rate);
}
 
public SampleUnifiedNativeAdMapper(SampleNativeAd ad) {
  sampleAd = ad;
  setHeadline(sampleAd.getHeadline());
  setBody(sampleAd.getBody());
  setCallToAction(sampleAd.getCallToAction());
  setStarRating(sampleAd.getStarRating());
  setStore(sampleAd.getStoreName());
  setIcon(new SampleNativeMappedImage(ad.getIcon(), ad.getIconUri(),
      SampleAdapter.SAMPLE_SDK_IMAGE_SCALE));
  setAdvertiser(ad.getAdvertiser());

  List<NativeAd.Image> imagesList = new ArrayList<NativeAd.Image>();
  imagesList.add(new SampleNativeMappedImage(ad.getImage(), ad.getImageUri(),
      SampleAdapter.SAMPLE_SDK_IMAGE_SCALE));
  setImages(imagesList);

  if (sampleAd.getPrice() != null) {
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String priceString = formatter.format(sampleAd.getPrice());
    setPrice(priceString);
  }

  Bundle extras = new Bundle();
  extras.putString(SampleAdapter.DEGREE_OF_AWESOMENESS, ad.getDegreeOfAwesomeness());
  this.setExtras(extras);

  SampleMediaView mediaView = sampleAd.getMediaView();

  // Some ads from Sample SDK have video assets and some do not.
  if (mediaView != null) {
    setMediaView(mediaView);
    setHasVideoContent(true);
  } else {
    setHasVideoContent(false);
  }

  setOverrideClickHandling(false);
  setOverrideImpressionRecording(false);

  setAdChoicesContent(sampleAd.getInformationIcon());
}
 
源代码20 项目: astor   文件: ExtendedMessageFormatTest.java
/**
 * Test extended and built in formats.
 */
public void testExtendedAndBuiltInFormats() {
    Calendar cal = Calendar.getInstance();
    cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
    Object[] args = new Object[] {"John Doe", cal.getTime(), new Double("12345.67")};
    String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
    String extendedPattern = "Name: {0,upper} ";
    String pattern = extendedPattern + builtinsPattern;

    HashSet<Locale> testLocales = new HashSet<Locale>();
    testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales()));
    testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
    testLocales.add(null);

    for (Iterator<Locale> l = testLocales.iterator(); l.hasNext();) {
        Locale locale = l.next();
        MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
        String expectedPattern = extendedPattern + builtins.toPattern();
        DateFormat df = null;
        NumberFormat nf = null;
        ExtendedMessageFormat emf = null;
        if (locale == null) {
            df = DateFormat.getDateInstance(DateFormat.SHORT);
            nf = NumberFormat.getCurrencyInstance();
            emf = new ExtendedMessageFormat(pattern, registry);
        } else {
            df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
            nf = NumberFormat.getCurrencyInstance(locale);
            emf = new ExtendedMessageFormat(pattern, locale, registry);
        }
        StringBuffer expected = new StringBuffer();
        expected.append("Name: ");
        expected.append(args[0].toString().toUpperCase());
        expected.append(" DOB: ");
        expected.append(df.format(args[1]));
        expected.append(" Salary: ");
        expected.append(nf.format(args[2]));
        assertPatternsEqual("pattern comparison for locale " + locale, expectedPattern, emf.toPattern());
        assertEquals(String.valueOf(locale), expected.toString(), emf.format(args));
    }
}