Convert a String to float in java - java

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

Related

How to parse "1,23$" in java using NumberFormat class and obtain 123 as number

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)

DecimalSeparator issue with String.Format()

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

java.lang.NumberFormatException while executing in France machine

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.FORMA‌​T)).getDecimalSepara‌​tor();
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?

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

How to write string with 3 significant digits without rounding

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.

Categories