Format currency without currency symbol
Asked Answered
H

16

76

I am using NumberFormat.getCurrencyInstance(myLocale) to get a custom currency format for a locale given by me. However, this always includes the currency symbol which I don't want, I just want the proper currency number format for my given locale without the currency symbol.

Doing a format.setCurrencySymbol(null) throws an exception..

Helbonna answered 28/12, 2011 at 16:2 Comment(7)
Have you tried .setCurrencySymbol("")?Calathus
@home: docs.oracle.com/javase/6/docs/api/java/text/…Calathus
When there is no need for the currency, why not using NumberFormat#getInstance( Locale ) ?Gloriagloriana
@home I was confused to.... DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();Macle
@home, the result is different. Example: when you use NumberFormat.getInstance(), the result could be "1,200", but when you use NumberFormat.getCurrencyInstance(), the result is "1,200.00"Impassion
For example, Swiss Francs learn.microsoft.com/en-us/globalization/locale/… Most currencies use the same decimal and thousands separator that the numbers in the locale use, but this is not always true. In some places in Switzerland, they use the period as a decimal separator for Swiss frans (Sfr. 127.54), but then use commas as the decimal separator everywhere else (127,54)Coulter
You should use the response described here https://mcmap.net/q/270567/-java-numbervalue-to-string-without-currency-signTolmann
G
72

The following works. It's a bit ugly, but it fulfils the contract:

NumberFormat nf = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol("");
((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
System.out.println(nf.format(12345.124).trim());

You could also get the pattern from the currency format, remove the currency symbol, and reconstruct a new format from the new pattern:

NumberFormat nf = NumberFormat.getCurrencyInstance();
String pattern = ((DecimalFormat) nf).toPattern();
String newPattern = pattern.replace("\u00A4", "").trim();
NumberFormat newFormat = new DecimalFormat(newPattern);
System.out.println(newFormat.format(12345.124));
Geier answered 28/12, 2011 at 16:18 Comment(4)
Until you use negative amounts, then it shows the Symbol again. I'm sure that must be a bug.Telestich
To fix the negative showing the currency, you can add the line: ((DecimalFormat) nf).setNegativePrefix(""+decimalFormatSymbols.getMinusSign());Siple
pattern.replace("\u00A4", "").trim() <-- This trim doesn't work because Java uses non-breaking space \u00A0 which is not removed by this method.Tigress
Nice Answer @ JBTreasonous
D
51

Set it with an empty string instead:

DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol(""); // Don't use null.
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(12.3456)); // 12.35
Decrescent answered 28/12, 2011 at 16:17 Comment(6)
this is equally right as well though can only chose one answer as the right one..Helbonna
I think the point is what Robin wrote: There is no need for getCurrencyInstance, just use getNumberInstanceHalpern
I think you might also need to set formatter.setMinimumFractionDigits(2); in your second example.Heligoland
@JoshDM: you shouldn't hardcode "2" here, unless you know you always want US Dollars, as the number of decimal points in currencies vary.Misogynist
@JoachimSauer I certainly can hardcode it in a 5-year old comment; I leave it up to the original requester to design a dynamic approach to setting the variable based on required Locale.Heligoland
I think the point is what Robin wrote: There is no need for getCurrencyInstance, just use getNumberInstance. Not true. See my comment on the OP.Coulter
D
9

Just use NumberFormat.getInstance() instead of NumberFormat.getCurrencyInstance() like follows:

val numberFormat = NumberFormat.getInstance().apply {
    this.currency = Currency.getInstance()
}

val formattedText = numberFormat.format(3.4)
Denice answered 8/1, 2020 at 22:36 Comment(1)
This returns a value #.# whereas getCurrencyInstance() returns #.##Callup
M
7

The given solution worked but ended up lefting some whitespaces for Euro for example. I ended up doing :

numberFormat.format(myNumber).replaceAll("[^0123456789.,]","");

This makes sure we have the currency formatting for a number without the currency or any other symbol.

Moly answered 25/4, 2019 at 14:35 Comment(3)
Love me some regex. Good solution using something simple like replaceAll while still being able to account for multiple formatsMillenarian
You might want to keep the minus sign (and also parenthesis) for negative numbers. currencyString.replaceAll("[^0123456789.,()-]","")Shamble
also some languages use an apostrophe (U+0027 or U+2019) as the thousands separator. So you might want to do currencyString.replaceAll("[^0123456789.,\(\)\-\x{0027}\x{2019}]","")Ossy
V
4

I still see people answering this question in 2020, so why not

NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(2); // <- the trick is here
System.out.println(nf.format(1000)); // <- 1,000.00
Vandyke answered 21/6, 2020 at 19:3 Comment(0)
D
3

Maybe we can just use replace or substring to just take the number part of the formatted string.

NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.getDefault());
fmt.format(-1989.64).replace(fmt.getCurrency().getSymbol(), "");
//fmt.format(1989.64).substring(1);  //this doesn't work for negative number since its format is -$1989.64
Doxy answered 16/4, 2018 at 20:53 Comment(0)
M
2
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
String formatted = df.format(num);

Works with many types for num, but don't forget to represent currency with BigDecimal.

For the situations when your num can have more than two digits after the decimal point, you could use df.setMaximumFractionDigits(2) to show only two, but that could only hide an underlying problem from whoever is running the application.

Magritte answered 12/10, 2016 at 20:23 Comment(0)
C
2

Most (all?) solutions provided here are useless in newer Java versions. Please use this:

DecimalFormat formatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.forLanguageTag("hr"));
formatter.setNegativeSuffix(""); // does the trick
formatter.setPositiveSuffix(""); // does the trick

formatter.format(new BigDecimal("12345.12"))
Cuckoo answered 25/2, 2020 at 10:33 Comment(1)
this also removes the minus sign for negative numbersOssy
T
0

Two Line answer

NumberFormat formatCurrency = new NumberFormat.currency(symbol: "");
var currencyConverted = formatCurrency.format(money);

In TextView

new Text('${formatCurrency.format(money}'),
Theatre answered 7/5, 2019 at 4:41 Comment(0)
H
0
NumberFormat numberFormat  = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.println("getCurrency = " + numberFormat.getCurrency());
        String number = numberFormat.format(99.123452323232323232323232);
        System.out.println("number = " + number);

Hispanicize answered 29/11, 2020 at 15:9 Comment(1)
try to explain your solution a bit, what was wrong in users code and what did you do to solve it.Credo
G
0

here the code that with any symbol (m2, currency, kilos, etc)

fun EditText.addCurrencyFormatter(symbol: String) {

   this.addTextChangedListener(object: TextWatcher {

        private var current = ""

        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            if (s.toString() != current) {
                [email protected](this)

                val cleanString = s.toString().replace("\\D".toRegex(), "")
                val parsed = if (cleanString.isBlank()) 0.0 else cleanString.toInt()

                val formatter = DecimalFormat.getInstance()

                val formated = formatter.format(parsed).replace(",",".")

                current = formated
                [email protected](formated + " $symbol")
                [email protected](formated.length)

                [email protected](this)
            }
        }
    })

}

-use with-

edit_text.addCurrencyFormatter("TL")
Gar answered 6/7, 2021 at 8:29 Comment(0)
P
0

In a function like this

 fun formatWithoutCurrency(value: Any): String {
    val numberFormat = NumberFormat.getInstance()
    return numberFormat.format(value)
}
Pond answered 2/5, 2022 at 18:26 Comment(0)
A
0

This does the trick for me. It shows it hardcoded for one locale, but you could pass in any locale as as both NumberFormat constructors use the same locale (and currency):

const locale = 'en-US';
const currency = 'USD';

const getCurrencySymbol = () =>
  (0)
    .toLocaleString(locale, {
      style: 'currency',
      currency: currency,
      maximumFractionDigits: 0,
      minimumFractionDigits: 0,
    })
    .replace(/\d/g, '')
    .trim();

const formattedNumberWithoutSymbol = new Intl.NumberFormat(locale, {
  style: 'currency',
  currency: currency,
}).format(499.99).replace(getCurrencySymbol(), '');

console.log(formattedNumberWithoutSymbol);
Arvizu answered 23/6, 2023 at 11:39 Comment(0)
I
0

Looks like a cleaner solution that doesn't alter the currency symbol in a hacky way:

val numberFormat = NumberFormat.getNumberInstance().apply {
    val priceFormat = NumberFormat.getCurrencyInstance()
    minimumFractionDigits = priceFormat.minimumFractionDigits
    maximumFractionDigits = priceFormat.maximumFractionDigits
}

For some reason, setting the currency in NumberFormat with Currency.getInstance() didn't work for me.

Insistency answered 10/11, 2023 at 8:56 Comment(0)
G
-2

there is a need for a currency format "WITHOUT the symbol", when u got huge reports or views and almost all columns represent monetary values, the symbol is annoying, there is no need for the symbol but yes for thousands separator and decimal comma. U need

new DecimalFormat("#,##0.00");

and not

new DecimalFormat("$#,##0.00");
Grady answered 3/10, 2013 at 13:42 Comment(3)
This is only helpful if the Locale is US, Canada, Australia, etc. It does not work for Sterling or Euro (where some countries use decimal points instead of commas for the thousand separator).Overstuffed
The post is not about using period or commas as thousand separators, u are off topicGrady
I still get for DecimalFormat df = new DecimalFormat("#,##0.00"); Exception in thread "main" java.text.ParseException: Unparseable number: "$400.00"Mendelian
T
-2

Please try below:

var totale=64000.15
var formatter = new Intl.NumberFormat('de-DE');
totaleGT=new Intl.NumberFormat('de-DE' ).format(totale)
Trafalgar answered 25/10, 2019 at 13:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.