Java Code Examples for java.text.NumberFormat#getCurrencyInstance()

The following examples show how to use java.text.NumberFormat#getCurrencyInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NumberFormatTest.java    From j2objc with Apache License 2.0 7 votes vote down vote up
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));
}
 
Example 2
Source File: Bug4651568.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 3
Source File: Bug4651568.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 4
Source File: CurrencyStyleFormatter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source File: Bug4651568.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 6
Source File: Bug4651568.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 7
Source File: CurrencyStyleFormatter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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;
}
 
Example 8
Source File: Bug4651568.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 9
Source File: Activity_Payment.java    From FoodOrdering with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 10
Source File: MessageFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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) {
  }
}
 
Example 11
Source File: CurrencyEditText.java    From FormattEditText with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: TestPeruCurrencyFormat.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 13
Source File: Helper.java    From mobikul-standalone-pos with MIT License 4 votes vote down vote up
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);
}
 
Example 14
Source File: SendDialogFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 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());
}
 
Example 15
Source File: Test6462562.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
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);
}
 
Example 16
Source File: DecimalFormatTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private String formatArbitraryCurrencyAmountInLocale(Currency currency, Locale locale) {
    NumberFormat localeCurrencyFormat = NumberFormat.getCurrencyInstance(locale);
    localeCurrencyFormat.setCurrency(currency);
    return localeCurrencyFormat.format(1000);
}
 
Example 17
Source File: Helper.java    From mobikul-standalone-pos with MIT License 4 votes vote down vote up
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);
}
 
Example 18
Source File: SampleUnifiedNativeAdMapper.java    From googleads-mobile-android-mediation with Apache License 2.0 4 votes vote down vote up
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());
}
 
Example 19
Source File: RoundingAndPropertyTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
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).");
        }
    }
 
Example 20
Source File: ExtendedMessageFormatTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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));
    }
}