Error NumberFormatException on Java - java

I have the following exception trying to manipulate a value to be added;
thank you very much for your help
java.lang.NumberFormatException: Invalid double: "20,000"
java.lang.StringToReal.invalidReal(StringToReal.java:63)
java.lang.StringToReal.parseDouble(StringToReal.java:269)
java.lang.Double.parseDouble(Double.java:295)
java.lang.Double.valueOf(Double.java:332)

You can use a NumberFormat to parse your String1. Something like,
String str = "20,000";
NumberFormat nf = NumberFormat.getNumberInstance(new Locale("en_US"));
NumberFormat nfIT = NumberFormat.getNumberInstance(Locale.ITALIAN);
try {
System.out.println(nf.parse(str)); // <-- 20000
System.out.println(nfIT.parse(str)); // <-- 20
} catch (ParseException e) {
e.printStackTrace();
}
For more options see Customizing Formats (The Java Tutorials).
1Being sure to pass the appropriate Locale to match your expected output.

You don't use comma as a separator in numbers.
You have to use 20000 instead of 20,000.
EDIT:
as #MitchWeaver mentioned, you can also substitute comma to underescore, making it 20_000

Related

com.ibm.icu.text.DecimalFormat always throws ParseException

With the following code I only want to allow positive numbers. For some reason i am not even able to parse the strings correctly:
DecimalFormat dfNoNegative = new DecimalFormat("#,##0.00");
dfNoNegative.setNegativePrefix("");
try {
System.out.println(dfNoNegative.parse("123.00"));
} catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println(e.getErrorOffset());
e.printStackTrace();
}
Error message and ErrorOffset:
Unparseable number: "123.00"
6
Can anyone guide me where I am mistaken? An example for a working String would be good as well
My mistake was to dfNoNegative.setNegativePrefix(""); to nothing (""). This doesn't work, because the String started directly with the number and 123 is not "", and therefore it fails. Basically this method overwrites what should be used as negative prefix (default is -). If you set it to ! as example, System.out.println(dfNoNegative.parse("!123.00")); would print -123.

Android Localization query

I have been working on localisation for my app and cant seem to find any information about how to handle decimal values and dates from different locals to store in sqllite.
for example:
German decimal 123,53
Uk decimal 123.53
So how do you convert from an edittext field to a valid decimal. At the moment I have my code outputting to a textview rather than sql just for testing. The below code works great when using UK decimal but if I use the german decimal it fails!!
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
NumberFormat nf = NumberFormat.getInstance(curLocale);
String convertedString = nf.format(Double.parseDouble(EditTextField.getText().toString()));
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
I have not started with dates yet but I am assuming converting dates for is more straight forward.
After some time working on this I found the solution for localisation, taking a value from input and parsing it to a format that can be understood by SQLlite - For this exercise and to reduce code I have just set it to output to a text view.
// set initial value to variables
String convertedString = "";
double parsedValue = 0.0;
//get value from text field
EditText EditTextField =(EditText)findViewById(R.id.TestNumericValueEntered);
String valueFromInput = EditTextField.getText().toString();
//Get current Locale from system
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
//Set number formats
NumberFormat nf_in = NumberFormat.getNumberInstance(curLocale);
NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);
//try to parse value, otherwise return error message
try {
parsedValue = nf_in.parse(valueFromInput).doubleValue();
// use nf_out.setMaximumFractionDigits(3) to set max number of digits allowed after decimal;
convertedString = nf_out.format(parsedValue);
}catch(ParseException e){
convertedString = "Unable to translate value";
}
//Output result
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
As I was adding this answer I realised that a nice addition to the code would be to check if the current locale is the same as the one you plan to parse to, if so then the conversion(parsing) can be skipped.

JFormattedTextField set value and text null after inputting wrong format

I'm working with Java Application with JFormattedTextField. I have some problems that:
How to set JFormattedTextField with can accept "/" and "-"
I want to set jformattedtextfield value and text to null or "" after entering wrong format.
Example:
2.1.JFormattedTextField ftf .... with format ("yyyy-MM-dd")
2.2. Input right format: 1990-5-6
2.3. Leave ftf
2.4. Then focus ftf and input wrong format: 5-6-1990
2.5. Leave ftf then it recognize wrong format but return something else
But what I want is that I must be null or empty.
How can I do it?
Any suggestions would be appreciated!
This is my first answer on this forum and I hope I don't mess up. For the first question, you can use MaskFormatter. This will also ensure that the value is never entered wrong.
new JFormattedTextField(createFormatter("####-##-##"));
private static MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(s);
formatter.setPlaceholderCharacter('0');
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}

Android : Error SimpleDateFormat Unknown pattern character 'u'

I use java 1.7.25
but found this error. what should I do?
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Unknown pattern character 'u'
at java.text.SimpleDateFormat.validateFormat(SimpleDateFormat.java:264)
at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:319)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:249)
Here is my code
public static int getDayNumberOfWeek(int day, String monthString, int yyyy) {
//http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
int dayNumberOfWeek = 1;
final String inputFormat = "MMM/dd/yyyy";
final String outputFormat = "u";
String dayString2Digit = DateTimeHelper.getTwoDigit(day);
String inputTimeStamp = monthString + "/" + dayString2Digit + "/" + String.valueOf(yyyy);
try {
dayNumberOfWeek =Integer.valueOf(TimeStampConverter(inputFormat, inputTimeStamp,
outputFormat));
}
catch (ParseException e) {
e.printStackTrace();
}
return dayNumberOfWeek;
}
I use java 1.7.25
No, you don't - not if you're running on Android. You need to look at the Android documentation, not the Java 7 docs.
If you look at the Android SimpleDateFormat documentation you'll see that u isn't listed there. I don't believe there's a format pattern character for "day of week as a number" in Android.
Were you really looking for that though? If you just want the day of the week as a number (without anything else) you can always use
String text = String.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
If you're using android, then you're not using Java 1.7.25. See the android documentation: there's no support for u in SimpleDateFormat.
I'm guessing your problem is going to be in your TimeStampConverter class where you're passing in that "u" as the outputFormat. "u" is not a valid format character in SimpleDateFormat and you must be constructing a format string that contains it.
If you need to use the "u" as a literal, you'll need to enclose it in single quotes.

Parsing a JSON Object in Java having special characters

I am stuck in a situation, where my JSONString (ruleFormJSONString) looks like :
{
"ruleDescription":"Test Rule2 Description",
"urlId":"1",
"listOfBusinessdays":["1","2","5","6","7"],
"status":"1",
"hierarchyId":"3",
"fromTime":"08:00",
"toTime":"18:00",
"dcnid":"1",
"eventId":"1",
"rowstate":"1",
"listOfLocations":["ASM","DEL"],
"ruleName":"Test Rule2",
"ruleId":"7","msgId":"1"
}
As you can see there are 2 attributes named fromTime and toTime which has a :
So while parsing this in Java, I used
JSONObject ruleFormJSON = JSONObject.fromString(ruleFormJSONString);
String fromTime = (String)ruleFormJSON.getString("fromTime");
String toTime = (String)ruleFormJSON.getString("toTime");
I am getting a NumberFormatException which is
java.lang.NumberFormatException: For input string: "18:00"
So please suggest me how, to get the value in the corresponding String variable.
Any help will be appreciated.
It seems there is an error on this line:
"listOfBusinessdays":"1","2","5","6","7"],
A closed bracket square but no open bracket before.
May be this hang up the parser.

Categories