java.lang.NumberFormatException while executing in France machine - java

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?

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

Convert a String to float in 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();

Format currency in Indian Numbering Format without symbol in java

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

How to format a Double from 1234567 to 1 234.567 in a safe manner

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

Categories