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);
Related
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);
I'm trying to parse a String to a float with the float.parsefloat() method but it gives me an error concerning the format.
int v_CurrentPosX = Math.round(Float.parseFloat(v_posString)); //where v_posString is the float that I want to convert in this case 5,828
And the error:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "5,828" at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
Your problem is that colon (,) is not a default locale in the JVM...
you can use a NumberFormat for that, with the right locale
String x = "5,828";
NumberFormat myNumForm = NumberFormat.getInstance(Locale.FRENCH);
double myParsedFrenchNumber = (double) myNumForm.parse(x);
System.out.println("D: " + myParsedFrenchNumber);
Try replacing the comma with a dot before parsing like so:
v_posString = v_posString.replace(",",".");
int v_CurrentPosX = Math.round(Float.parseFloat(v_posString));
The problem is that your locale is set to use . for floats and not ,.
Try this
NumberFormat.getNumberInstance(Locale.FRANCE).parse("5,828");
Float.parseFloat() doesn't consider locale and always expects '.' to be your decimal point separator. You can use DecimalFormat instead.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
String str = "5,200";
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
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();
I would like the convert string value with 3 significant digits.
I am using this code :
String s = "0,92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("#,###");
String end = formatter.format(f);
The result is end= 0.000. But ı want to get end = 0,920. How can i do that?
If in your current locale the decimal separator is a dot then you will get 0.920. If you want to get the result independent from you current locale to have as decimal separator a comma and as thousand separator a dot you could achieve it for example like this
String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String end = formatter.format(f);
System.out.println("end = " + end);
This prints
end = 0,920
This works for me:
String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000");
String end = formatter.format(f);
System.out.println(end);
Please note the '.' in the String s and the pattern in DecimalFormat.
',' here means the 1000 marker, ie. 1,000,000.00 for one million.
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;
}
}