how to convert currency format to double in java - java

I am getting value in currency formate, but i want double format only.
String amt = txn.getAmount();
System.out.println("--amt--"+amt);//output:1010
double value = Double.parseDouble(amt);
System.out.println("---value---"+value);//output:1010.0
String ammount=NumberFormat.getCurrencyInstance().format(value);
System.out.println("--ammount--"+ammount);//output:Rs.1,010.00
Here i want Rs.1,010.00 to 1010.00
Any mistakes in my code?

I assume you do not want the currency details. In that case, use getNumberInstance() instead of getCurrencyInstance().
Use:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(false);
nf.setMinimumFractionDigits(2);
String ammount= nf.format(value);

Before printing, replace the string "Rs." with "" and also "," with "".
String replaceString1=amount.replace("Rs.","");
String replaceString2=amount.replace(",","");
This is a way to handle this case.
Hope this helps.

Try this cleaner approach!.
double d = 1010.00;
Locale uk = new Locale("en", "GB");
NumberFormat cf = NumberFormat.getCurrencyInstance(uk);
String s = cf.format(d);
System.out.println(s);
Number number = null;
try
{
number = cf.parse(s);
}
catch (ParseException e)
{
System.out.print(e);
}
double dClone = number.doubleValue();

Related

Java - How to convert string to big decimal with money format

My string is "1234567" and I want to get two big decimal object like these
12345,67 and 12.345,67 but I couldn't do this. Code is shown as below:
DecimalFormat decimalFormat = new DecimalFormat("#,##0.###");
decimalFormat.setParseBigDecimal(true);
String n = decimalFormat.format(1234567);
BigDecimal bigDecimal = (BigDecimal)decimalFormat.parse(n);
DecimalFormat decimalFormat1 = new DecimalFormat("#,0#");
decimalFormat1.setParseBigDecimal(true);
String n1 = decimalFormat.format(1234567);
BigDecimal bigDecimal1 = (BigDecimal)decimalFormat.parse(n1);
System.out.println(n);
System.out.println(bigDecimal);
System.out.println(n1);
System.out.println(bigDecimal1);
Output:
1.234.567,00
1234567.00
1.234.567,00
1234567.00
Expected output:
12.345,67
12.345,67
12345,67
12345,67
Thank you for your help
Number formatting is always locale specific. Therefore a defined locale is needed.
Following approach will work for the formatting:
BigDecimal money = new BigDecimal("1234567");
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
// https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
DecimalFormat format = new DecimalFormat("###,###.00");
format.setDecimalFormatSymbols(symbols);
System.out.println(format.format(money));
However, this does not meet the requirement to parse any given number as a decimal with 2 digits. Here, I would personally would apply a division by 100 or, insert a decimal separator into the given String.
BigDecimal money = new BigDecimal("1234567").divide(new BigDecimal("100"));
Inserting a defined decimal separator could work like this:
private static String prepare(String input) {
if (input.length() == 2) {
return ","+input;
}
if (input.length() == 1) {
return ",0"+input;
}
String integerPart = input.substring(0, input.length()-2);
String fraction = input.substring(input.length()-2);
return integerPart+","+fraction;
}
Using the new DecimalFormat and the prepare() method it would work to parse a String as a number with 2 decimals by default.
String input = "1234567";
String prepared = prepare(input);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
DecimalFormat format = new DecimalFormat("###,###.00");
format.setDecimalFormatSymbols(symbols);
format.setParseBigDecimal(true);
BigDecimal bigDecimal = (BigDecimal)format.parse(prepared);
String n = format.format(bigDecimal);
System.out.println(n);

convert String to double with '%'

I have a String value like "1.22%". I want to convert this to double value.
Douboe.parseDouble throws numberFormatException.
String s = "1.22%";
double iRate;
iRate = Double.parseDouble(s);
One-liner using DecimalFormat:
double d = new DecimalFormat("0.0#%").parse("1.22%").doubleValue();
// d = 0.0122
You want to use a method similar to the one below:
public static double ConvertPercentageStringToDouble(this string value)
{
return double.Parse(value.Replace("%","")) / 100;
}
Assuming you have standard format. You can try
String s = "1.22%";
s = s.replaceAll("%","");
double iRate= Double.parseDouble(s);
The better way to do this is using DecimalFormatSymbols, which can help you to define what is simbols and what is really numbers to transform into Double.
See the example below:
String s = "1.22%";
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
symbols.setPercent('%');
df.setDecimalFormatSymbols(symbols);
Number parse = df.parse(s);
Double myDouble = parse.doubleValue();
System.out.println(myDouble);

Converting string value with comma to Decimal with correct Locale

I am trying to create Double object from decimal string value where comma is floating separator.
Passing locale arguments to vm:
-Duser.country=BR
-Duser.language=PT
String value = "500,21";
Double dob = new Double(value);
Getting exception:
java.lang.NumberFormatException: For input string: "500,21" at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.valueOf(Double.java:475) at
java.lang.Double.(Double.java:567)
You can try with a localized NumberFormat:
String value = "500,21";
// replace the hard-coded Locale definition with your arguments, or
// Locale.getDefault(), etc.
NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "BR"));
try {
Double d = nf.parse(value).doubleValue();
System.out.println(d);
}
catch (ParseException pe) {
// TODO
}
Output
500.21
It looks like that new Double(value) does not take into consideration the locale setting.
The implementation ends up calling this method here and it is only looking for ".".
With the locale set as you did you can use this:
NumberFormat.getInstance().parse(value).doubleValue()
Here is a similar discussion.

need space between currency symbol and amount

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

Convert String with Dot or Comma to Float Number

I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .
How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the '.')? Does this depend on local computer settings?
The Float.parseFloat() method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.
The NumberFormat class provides locale-aware parse and format should you need to adapt for different locales.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
valueStr = valueStr.replace(',', '.');
return new Float(valueStr);
Done
See java.text.NumberFormat and DecimalFormat:
NumberFormat nf = new DecimalFormat ("990.0");
double d = nf.parse (text);
What about this:
Float floatFromStringOrZero(String s){
Float val = Float.valueOf(0);
try{
val = Float.valueOf(s);
} catch(NumberFormatException ex){
DecimalFormat df = new DecimalFormat();
Number n = null;
try{
n = df.parse(s);
} catch(ParseException ex2){
}
if(n != null)
val = n.floatValue();
}
return val;
}
You can use the placeholder %s-String for any primitive type.
float x = 3.15f, y = 1.2345f;
System.out.printf("%.4s and %.5s", x, y);
Output: 3.15 and 1.234
%s is always english formatting regardless of localization.
If you want a specif local formatting, you could also do:
import java.util.Locale;
float x = 3.15f, y = 1.2345f;
System.out.printf(Locale.GERMAN, "%.2f and %.4f", x, y);
Output: 3,15 and 1,2345
I hope this piece of code may help you.
public static Float getDigit(String quote){
char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
if (String.valueOf(decimalSeparator).equals(",")) {
valueOnlyDigit = valueOnlyDigit.replace(",", ".");
//Log.i("debinf purcadap", "substituted comma by dot");
}
try {
return Float.parseFloat(valueOnlyDigit);
} catch (ArithmeticException | NumberFormatException e) {
//Log.i("debinf purcadap", "Error in getMoneyAsDecimal", e);
return null;
}
}

Categories