I already tried some stuff but without success. Is there no simple decimal format for this ?
The first solution does the trick but i do not want to have the symbol
Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println(format.format(new BigDecimal("1000000")));
The second solution with decimal format gives me trouble when there are numbers after the separator.
DecimalFormatSymbols symbols5 = new DecimalFormatSymbols();
symbols5.setDecimalSeparator('.');
symbols5.setGroupingSeparator(',');
NumberFormat goodNumberFormat5 = new DecimalFormat("##,##,##1", symbols5);
System.out.println("************");
System.out.println("10,00,000.00");
System.out.println("************");
System.out.println(goodNumberFormat5.format(new BigDecimal(1000000)));
System.out.println(goodNumberFormat5.format(new BigDecimal(1000000.00)));
System.out.println();
The output of this is :
? 10,00,000.00
************
10,00,000.00
************
1,00,00,001
1,00,00,001
How could i fix this ?
The excepted output should be 10,00,000.00
With a bit of help from RC i found this solution.
Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
String str = format.format(1000000);
String strWithoutSymbol = "";
strWithoutSymbol = str.substring(1,str.length());
System.out.println(strWithoutSymbol);
Related
I tried the following code samples, but did not work,
NumberFormat.getCurrencyInstance(Locale.US).parse("1,23$")
throws below exception
java.text.ParseException: Unparseable number: "1,23$"
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("$");
dfs.setGroupingSeparator('.');
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
final Number parse = df.parse("1,23$");
System.out.println(parse);
You can't check both with one number format. You would need to try one if the other fails:
DecimalFormat format1 =
(DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
format1.applyPattern("##,#0¤");
DecimalFormat format2 =
(DecimalFormat)NumberFormat.getNumberInstance(Locale.US);
format2.applyPattern("¤##,#0");
System.out.println(format1.parse("1,23$"));
System.out.println(format2.parse("$1,23"));
This uses the currency pattern placeholder ¤.
Seems like you want this
public int getValue(String s) {
return Integer.parseInt(s.replaceAll("\\p{Punct}", ""));
}
Reformat your string.
String s = "1,23$";
s = '$' + s.replaceAll("\\p{Punct}", "");
System.out.println(NumberFormat.getCurrencyInstance(Locale.US).parse(s));
Number number = NumberFormat.getCurrencyInstance(Locale.US).parse("$1,23");
System.out.println("Number is "+ number ) ;
And Output is
Number is 123
if you pass value 1,23$
Exception in thread "main" java.text.ParseException: Unparseable number: "1,23$"
at java.text.NumberFormat.parse(NumberFormat.java:385)
at com.example.polls.PollsApplicationTests.main(PollsApplicationTests.java:18)
Please find my code below:
double value = (double)-16325.62015;
System.out.println(String.format("%s", value));//-16325.62015
System.out.println(String.format(new Locale("de", "DE"), "%s", value));//-16325.62015
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(new Locale("de", "DE"));
System.out.println(dfs.getDecimalSeparator());//,
In the above code, Im getting the wrong decimal separator for German locale.
I have tried the below code also but it produces -16325,6
double value = (double)-16325.62015;
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(new Locale("de", "DE"));
DecimalFormat df = new DecimalFormat("#.#", dfs );
System.out.println(df.format(value));
is there any alternative way to print the output as -16325,62015
Note: I want to print double value with n number of decimal places for any specific locale
Thanks in advance
You must use %f not %s. When %s is used, Java converts your value to String using String.valueOf which uses the default locale.
double value = (double)-16325.62015;
System.out.println(String.format("%f", value));
System.out.println(String.format(Locale.GERMANY, "%f", value));
In below code while parsing the value sometimes i am facing NumberFormat Exception in France machine.
double txPower;
DecimalFormat df = new DecimalFormat("##.##");
txPower = txPower + getDeltaP();
log.info("txpower value is -- "+txPower);
txPower = Double.parseDouble(df.format(txPower));
protected double getDeltaP()
{
return isNewChannelAddition ? apaConfig.deltaPadd : apaConfig.deltaPtune;
}
logs:
txpower value is -- -7.9
java.lang.NumberFormatException: For input string: "-7,9"
I suggest to use the decimal separator configured as default for your locale.
new DecimalFormatSymbols(Locale.getDefault(Locale.Category.FORMAT)).getDecimalSeparator();
You have to ways to solve your problem :
One, you can use replace(",", ".") like this :
txPower = Double.parseDouble(df.format(txPower).replace(",", "."));
Two, you can use the local for the DecimalFormat :
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyLocalizedPattern("##.##");
txPower = txPower + getDeltaP();
txPower = Double.parseDouble(df.format(txPower));
You can also call something like this String.format("%.2f", -7.9)
Double.parseDouble doesn't support locale-specific decimal points (see the doc here). Try using your DecimalFormat to parse instead:
txPower = df.parse(df.format(txPower)).doubleValue();
Having said that, I must ask what you are hoping to gain by to turning the double value txPower into a String, parsing the string into a double and putting the result back into txPower?
All in the title.., I'm looking for a safe way to format all Double in this manner, some other examples:
1000 ==> 1.000
1500 ==> 1.500
22000 ==> 22.000
1555005 ==> 1 555.005
I have looked in this link but not helped...
there is a safe way to do that ? THX in advance
You want to print your input number divided by a thousand, using a decimal dot and space as thousand separator. The safe way is to first convert to BigDecimal, scale by 10-3, then print it using DecimalFormat.
final DecimalFormat f = new DecimalFormat("#,###.000");
final DecimalFormatSymbols s = new DecimalFormatSymbols();
s.setGroupingSeparator(' ');
s.setDecimalSeparator('.');
f.setDecimalFormatSymbols(s);
final double input = 1_555_005;
final BigDecimal x = new BigDecimal(input).scaleByPowerOfTen(-3);
System.out.println(f.format(x));
prints
1 555.005
Note that setting grouping/decimal separators explicitly like here is not the orthodox way to do this: normally you would let the Locale setting dictate the number format.
this is taken from here
static public void displayNumber(Locale currentLocale) {
Integer quantity = new Integer(123456);
Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String quantityOut;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut + " " + currentLocale.toString());
System.out.println(amountOut + " " + currentLocale.toString());
}
This example prints the following; it shows how the format of the same number varies with Locale:
123 456 fr_FR
345 987,246 fr_FR
123.456 de_DE
345.987,246 de_DE
123,456 en_US
345,987.246 en_US
Always use the java formatting API. There is a nice tutorial on number formatting at - http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html.
You can get a locale based formatter for French and format:
NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
For French the output will be something like this:
###,###.### 123 456,789 fr_FR
I'm trying to print INR format currency like this:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);
shows Rs30,382.50, but in India its written as Rs. 30,382.50(see http://www.flipkart.com/)
how to solve without hardcoding for INR?
It's a bit of a hack but in a very similar situation, I used something like this
NumberFormat format = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
String currencySymbol = format.format(0.00).replace("0.00", "");
System.out.println(format.format(30382.50).replace(currencySymbol, currencySymbol + " "));
all the currencies I had to deal with involved two decimal places so i was able to do "0.00" for all of them but if you plan to use something like Japanese Yen, this has to be tweaked. There is a NumberFormat.getCurrency().getSymbol(); but it returns INR instead for Rs. so that cannot be used for getting the currency symbol.
An easier method, kind of workaround.
For my locale, the currency symbol is "R$"
public static String moneyFormatter(double d){
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
Locale locale = Locale.getDefault();
String symbol = Currency.getInstance(locale).getSymbol(locale);
fmt.setGroupingUsed(true);
fmt.setPositivePrefix(symbol + " ");
fmt.setNegativePrefix("-" + symbol + " ");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
return fmt.format(d);
}
Input:
moneyFormatter(225.0);
Output:
"R$ 225,00"
See if this works:
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
fmt.setGroupingUsed(true);
fmt.setPositivePrefix("Rs. ");
fmt.setNegativePrefix("Rs. -");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
fmt.format(30382.50);
Edit: Fixed the first line.
I dont think you can.
You should take a look at http://site.icu-project.org/
There might be better locale-specific currency formatting provided by icu4j.
I don't see any easy way to do this. Here's what I came up with...
The key to getting the actual currency symbol seems to be passing the destination locale into Currency.getSymbol:
currencyFormat.getCurrency().getSymbol(locale)
Here's some code that seems like it mostly works:
public static String formatPrice(String price, Locale locale, String currencyCode) {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
Currency currency = Currency.getInstance(currencyCode);
currencyFormat.setCurrency(currency);
try {
String formatted = currencyFormat.format(NumberFormat.getNumberInstance().parse(price));
String symbol = currencyFormat.getCurrency().getSymbol(locale);
// Different locales put the symbol on opposite sides of the amount
// http://en.wikipedia.org/wiki/Currency_sign
// If there is already a space (like the fr_FR locale formats things),
// then return this as is, otherwise insert a space on either side
// and trim the result
if (StringUtils.contains(formatted, " " + symbol) || StringUtils.contains(formatted, symbol + " ")) {
return formatted;
} else {
return StringUtils.replaceOnce(formatted, symbol, " " + symbol + " ").trim();
}
} catch (ParseException e) {
// ignore
}
return null;
}
Sorry for Kotlin I came here from android).
As I understood there is no correct solutions for that, so that's why my solution is also hack)
fun formatBalance(
amount: Float,
currencyCode: String,
languageLocale: Locale
): String {
amount can be String as well.
val currencyFormatter: NumberFormat = NumberFormat.getCurrencyInstance(languageLocale)
currencyFormatter.currency = Currency.getInstance(currencyCode)
val formatted = currencyFormatter.format(amount)
formatted will get amount with currency from correct side but without space. (Example: 100$, €100)
val amountFirstSymbol = amount.toString()[0]
val formattedFirstSymbol = formatted[0]
val currencySymbolIsBefore = amountFirstSymbol != formattedFirstSymbol
Then I use this little hack to understand if currency symbol is before amount. So for example amount is 100 then amountFirstSymbol will be "1". And if formatted is 100$ then formattedFirstSymbol also will be "1". That means we can put our currency symbol behind amount but now with space.
val symbol = currencyFormatter.currency?.symbol
return if (currencySymbolIsBefore) "$symbol $amount"
else "$amount $symbol"
Here what I do to add space after currency symbol:
DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("id", "ID"));
DecimalFormatSymbols symbol = new DecimalFormatSymbols(new Locale("id", "ID"));
// Add space to currency symbol
symbol.setCurrencySymbol(symbol.getCurrencySymbol() + " ");
numberFormat.setDecimalFormatSymbols(symbol);