Format currency without currency symbol - java

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..

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));

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

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.

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)

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

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

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.

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"))

Two Line answer
NumberFormat formatCurrency = new NumberFormat.currency(symbol: "");
var currencyConverted = formatCurrency.format(money);
In TextView
new Text('${formatCurrency.format(money}'),

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.UK);
System.out.println("getCurrency = " + numberFormat.getCurrency());
String number = numberFormat.format(99.123452323232323232323232);
System.out.println("number = " + number);

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) {
this#addCurrencyFormatter.removeTextChangedListener(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
this#addCurrencyFormatter.setText(formated + " $symbol")
this#addCurrencyFormatter.setSelection(formated.length)
this#addCurrencyFormatter.addTextChangedListener(this)
}
}
})
}
-use with-
edit_text.addCurrencyFormatter("TL")

In a function like this
fun formatWithoutCurrency(value: Any): String {
val numberFormat = NumberFormat.getInstance()
return numberFormat.format(value)
}

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");

Please try below:
var totale=64000.15
var formatter = new Intl.NumberFormat('de-DE');
totaleGT=new Intl.NumberFormat('de-DE' ).format(totale)

Related

How to format currency with number format classes

I am new in Android development and i am stuck at a place. I want to format my currency, I am setting to show without decimal places and with commas.
Example: right now it's showing like 23000.00. But I want the currency like 23,000; how can I do that?
I tried the formatter classes but that doesn't help me.
This is how it's set now.
public class CurrencyFormatter {
public static String setsymbol(BigDecimal data, String currency_symbol)
{
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
format.setCurrency(Currency.getInstance(currency_symbol));
String result=data+" "+" دينار";
return result;
}
}
I expect output to be (arabic text)23,000 instead of (arabic test)23000.00
Basically, you need a currency formatter object.
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
After that you can format an amount of money:
Double currencyAmount = new Double(23000.00);
String formattedOutput = currencyFormatter.format(currencyAmount);
There are more options and explanations available here on Oracle's reference document: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
check this
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setCurrency(Currency.getInstance("USA"));
String result = format.format(1234567.89);
This is the format set of usa you can change with your country code
reference check description here
Try this, it will show in this format 23,000 without decimal points, It will show thousand separator in the number.
String result = null;
try {
// The comma in the format specifier does the trick
result = String.format("%,d", Long.parseLong(data)); // use this result variable where you want to use.
result = result + " " + " دينار"; // to append arabic text, do as you were doing before.
} catch (NumberFormatException e) {
}

Is locale aware parsing for Numberformat possible in Android?

I have an Android application which does some basic mathematics.
Example
try {
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat) nf;
a = Float.parseFloat(vw3.getText().toString());
f = Float.parseFloat(vw5.getText().toString());
c = a / 100;
d = c * 1.036f;
e = f / 100;
g = e * 1.24f;
h = d + g;
String str1 = String.valueOf(df.format(h));
vw7.setText(str1);
} catch (NumberFormatException f) {
a = (0);
}
}
When the user is in the USA the calculations work fine and format fine. Well as you would expect. The 1,000.00 format where the grouping is by comma and separator is by decimal point. When a user is in France, the grouping is different and the separator is also different. Using the 1,000.00 example, in France the number would be formatted like this 1 000,00. A space is the grouping separator and the comma is the decimal separator. This causes a problem when you try and run a calculation and you will get a NumberFromatException (NFE). And I anticipated a NFE issue and catch it and replace the possible cause with the correct number. However, replacing any comma with a space and any period with a comma will also produce a NFE.
Example
try {
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat) nf;
a = Float.parseFloat(vw3.getText().toString().replace(",",""));
f = Float.parseFloat(vw5.getText().toString().replace(",",""));
c = a / 100;
d = c * 1.036f;
e = f / 100;
g = e * 1.24f;
h = d + g;
String str1 = String.valueOf(df.format(h));
vw7.setText(str1);
} catch (NumberFormatException f) {
a = (0);
}
}
EDIT - As suggested by Peter O. I have tried parsing the number with a locale aware means.
Example
NumberFormat.getNumberInstance().parse(string);
Or
NumberFormat df = NumberFormat.getNumberInstance();
String value = "10,40 €";
Number valueParsed = df.parse(value);
vw7.setText(valueParsed);
Will produce a "Bad Class" illegalargument.
I am looking for a solution to where I can do the calculations in an acceptable manner within the apps programming regardless of the locale and then later format the results to the locale. The question could be or is, do you force a locale for your calculations and then format the results for the locale?
If this is the code you are using and your strings will have the currency symbol. In this case € the EURO symbol.
Your example:
NumberFormat df = NumberFormat.getNumberInstance();
String value = "10,40 €";
Number valueParsed = df.parse(value);
vw7.setText(valueParsed);
so that value always has a currency symbol you need to use
NumberFormat df= NumberFormat.getCurrencyInstance();
instead of the .getNumberInstance(). This worked on my system which is currently set so that the € symbols is the default currency symbol. You will have to try it on a system that has the $ currency symbol in order to verify that it works there, also.

Regex to format a string in a valid big decimal value

Dear friends I'reading a csv file that contains some file like this 1.086,12. Now my problem is that I have to format it a way that allows my to create a BigDecimal, them my correct value should be 1086.12. But I could also have another value 99,11 and in this case I have to get 99.11.
I write this snippet of code:
BigDecimal bigDecimal = null;
String str = value.replace(',','.');
bigDecimal = new BigDecimal(str);
My code works just in the latter cese, Is there some regular expression that allows this?
You do not need a regex. You can/should use DecimalFormat for that:
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.GERMAN);
DecimalFormat df= new DecimalFormat();
df.setDecimalFormatSymbols(dfs);
Double valCEWithUKFormat = df.parse(str).doubleValue();
You can use this Java code:
String[] arr = {"1.086,12", "99.11"};
for (String tok: arr) {
if (tok.matches("[^.]*\\.[^,]+,.*"))
tok= tok.replace(".", "").replace(",", ".");
System.out.println( tok );
}
output:
1086.12
99.11

Formating a number to two decimals without rounding up and converting to Double

I know this has been questioned alot of times but i tried all solutions in other threads and i cant find one that matches what i want ...
So i have one input something like this -9.22841 which is read as a String, what i want to do is to format this number to two decimals like this -9.23 without rounding it up and then converting it to double without losing this format...
I have tried many ways like String.format("%.2f",number) and the one below ...
String l = -9.22841
DecimalFormat df = new DecimalFormat("#,00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
and this one:
String l = -9.22841
DecimalFormat df = new DecimalFormat("#.00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
but everytime i try to convert to double in the String.format("%.2f",number) or DecimalFormat df = new DecimalFormat("#.00"); gives error converting to double
and when i do this :
DecimalFormat df = new DecimalFormat("#,00");
The output is wrong and is something like this -9.23 where it should be -9.22
Thanks for your time ...
You could just chop off the String two spaces after the decimal:
String number = "-9.22841";
String shorterNumber = number.substring(0, number.indexOf(".")+3);
double t = Double.parseDouble(shorterNumber);
System.out.println(t);
Thats what you want:
String number = "-9.22841";
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.DOWN);
number = formatter.format(Double.valueOf(number));
System.out.println(number);
The output will be:
-9,22
You can use bellow function:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public static double formatValue(Double number) {
DecimalFormat df = new DecimalFormat("####0.00");
df.setRoundingMode(RoundingMode.DOWN);
return Double.parseDouble(df.format(number));
}
Input = 31.6227890 ,
OutPUT = 31.62
For someone looking full decimal handling:Kotlin
fun validateNumber(number: String): String {
return if (number.contains(".") && number.length > 3+number.indexOf("."))
number.substring(0, number.indexOf(".")+3)
else if (number.contains(".")){
number.substring(0, number.indexOf(".")+2)+"0"
}else{
"$number.00"
}
}

Number/Currency Formatting

I do have Bulgarian currency in a format like +000000027511,00.I want to convert this format to 27511.00,I have tried it and got using substring combinations and regex,Is there any patterns or regex to do it in more simplified way?
Implementation I tried,
String currency= "+000000027511"; // "[1234]" String
String currencyFormatted=currency.substring(1);
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", ""));
Using Double.valueOf + DecimalFormat.format, or DecimalFormat.parse + format, or BigDecimal you can do it as this.
// method 1 (parsing to Float)
String s = "+000000027511,00".replace(",", ".");
Double f = Double.valueOf(s);
DecimalFormat df = new DecimalFormat("#########0.00");
String formatted = df.format(f);
System.out.println(formatted);
// method 2 (parsing using Decimal Format)
s = "+000000027511,00";
DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00");
Number n = df2.parse(s);
df = new DecimalFormat("#########0.00");
formatted = df.format(n);
System.out.println(formatted);
// method 3 (using BigDecimal)
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
Will print
27511.00
27511.00
27511.00
Something like this:
String s = "+000000027511,00";
String r = s.replaceFirst("^\\+?0*", "");
r = r.replace(',', '.');
Try
String s = "+000000027511,00";
s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.');
System.out.println(s);

Categories

Resources