I'm getting the following error when trying to parse the phone number, "5554567899"
java.lang.NumberFormatException: For input string: "5554567899"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
...
Obviously, the phone number is able to be parsed. I even referenced this question, and the byte code result was
53,53,53,52,53,54,55,56,57,57,
So there's no invisible characters in the string. I'm stumped, can anyone help?
Here's the section of the code that's throwing the error, for reference:
String fullNumber = null;
for(Phone phone : party.getPhones()) {
if(phone != null && !phone.getDialNumber().isEmpty()) {
if(!phone.getAreaCode().isEmpty()) {
fullNumber = phone.getAreaCode();
}
fullNumber += phone.getDialNumber();
if(phone1 == null || phone1.equals(0)) {
LOGGER.debug(displayCharValues(fullNumber));
phone1 = Integer.parseInt(fullNumber);
}
}
phone1 is of Java.lang.Integer type.
The value exceeds the int range. Parse it into a long variable.
Simple test:
int i = 5554567899;
is a compile time error: "The literal 5554567899 of type int is out of range"
Really a phone number shouldn't be treated as a number at all, but as a string or possibly as a datatype that you define yourself, breaking out the country code, area code, exchange, etc.
If you want to validate that it contains only numbers or numbers plus some of the standard phone-number separators, this can be done by regular expressions.
We call it a phone number, and it is a numeric string, but as the usage isn't for numeric computation, you're better off never trying to treat it as a number.
The same goes for "social security numbers".
5554567899 as a number is too big to fit in an int. Try Long.parseLong instead.
5554567899 exceeds Integer.MAX_VALUE (2147483647). Use Long or BigInteger instead:
BigInteger bigNumber = new BigInteger("5554567899");
Related
I have seen several questions on the topic mentioned in the subject (e.g this one), but it seems to me that none of them provided this example. I'm using Java7 and I want to convert a String representing an hexadecimal or a decimal into an Integer or Long value (depends on what it represents) and I do the following:
public Number getIntegerOrLong(String num) {
try {
return Integer.decode(num);
} catch (NumberFormatException nf1) {
final long decodedLong = Long.decode(num);
if ((int) decodedLong == decodedLong) {//used in Java8 java.util.Math.toIntExact()
return (int) decodedLong;
}
return decodedLong;
}
}
When I use a String representing a decimal number everything is ok, the problem are arising with negative hexadecimals
Now, If I do:
String hex = "0x"+Integer.toHexString(Integer.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Integer):
fails, because it returns a Long. Same for other negative integer values.
Moreover, when I use Long.MIN_VALUE like in the following:
String hex = "0x"+Integer.toHexString(Long.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Long):
fails, because of NumberFormatException with message:
java.lang.NumberFormatException: For input string: "8000000000000000"
I also tried with other random Long values (so within the Long.MIN_VALUE and Long.MAX_VALUE, and it fails as well when I have negative numbers. E.g.
the String with the hexadecimal 0xc0f1a47ba0c04d89 for the Long number -4,543,669,698,155,229,815 returns:
java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
How can I fix the script to obtain the desired behavior?
Long.decode and Integer.decode do not accept complemented values such as returned by Integer.toHexString : the sign should be represented as a leading - as described by the DecodableString grammars found in the javadoc.
The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Long.parseLong method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign
If you can change the format of your input String, then produce it with Integer.toString(value, 16) rather than Integer.toHexString(value).
If you can switch to Java 8, use parseUnsignedInt/Long.
I have some issue like this
in my textview Rs. 99.99
String val = textview.getText().toString();
Result :: val :: Rs.99.99
i am converting that into float using this way
float value = Float.parseFloat(val);
i am getting NumberFormatException: Rs.99.99 cannot convert
any one guide me
You can do the following before converting it to float
String substring = str.length() > 2 ? str.substring(str.length() - 3) : str;
You can try this way.
System.out.println(Float.parseFloat("Rs.99.99".substring(3)));
Note: You need to make sure the string always contain "Rs." in the beginning.
i am getting numberFormat Exception Rs.99.99 cannot convert
Yes, because in method
Float.parseFloat(String s);
You get
NumberFormatException -- if the string does not contain a parsable float.
And In your case it isn't,
So best option is to apply Validation to enter only floating point numbers inside text View.
It's not entirely clear what the problem is (do all the strings that cause problems begin with Rs., or are users putting other kinds of garbage at the beginning of the input)? Here's a way to remove all characters from the string, up to (but not including) the first digit:
val = val.replaceFirst("^[^0-9]*", "");
This finds the first occurrence of a pattern that starts at the beginning of the string (the first ^) and consists of 0 or more occurrences of nondigits ([^0-9]).
I'm trying to ensure that a given string is a valid double. Most answers to this sort of question suggest using Double.parseDouble(inputString). However this isn't as robust as I'd hope. For instance if I enter a String such as "1one" Double.parseDouble("1one") will output "1" as opposed to returning an exception for an invalid double.
I've tried to get around this by iterating over the string and ensuring that every number is a digit:
for (int i = 0; i < number.length(); i++) {
previousChar = number.charAt(i);
if (!Character.isDigit(number.charAt(i))
&& number.charAt(i) != '.'
&& number.charAt(i) != ',') {
return null;
}
}
But for cases such as "20..02" or "20,,02" this will simply return 20. I was wondering what the best way to account for cases such as these would be.
Good question. Depending on the users, you may need to be careful of differences between locales. Some places use , as a thousand separator others as a decimal point. You can find the locale-specific value using:
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
char decimalSeparator = symbols.getDecimalSeparator();
I would suggest writing a regular expression for your exact requirement rather than doing the matching manually. Remember to escape . if you want it to match . and not "any character".
Alternatively, you may be able to use parseDouble which does seem to throw an exception for "1one" after all:
System.out.println(Double.parseDouble("1one"));
For me, it produces:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1one"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
You could use the Validator framework and use the DoubleValidator from commons-validator.
DoubleValidator validator = DoubleValidator.getInstance();
validator.validate("1one");
Parsing strings to doubles is fraught with danger. For example, in France, 1,234 is a number just a little greater than 1. They use . to separate round thousands and , to denote the start of the decimal portion.
The best way to check if a string is a valid number is to use NumberFormat to attempt to parse it and treat any exceptions thrown as an indication that the string is not a valid number. NumberFormat allows you to associate a locale:
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH/*for example*/);
double myNumber = nf.parse(myString); /*will throw an exception if not valid*/
I would use Double.parseDouble, because, contrary to what you believe, it does throw a NumberFormatException for 1one.
public class k {
public static void main(String argv[]) {
double d = Double.parseDouble("1one");
}
}
Output:
Exception in thread "Main Thread" java.lang.NumberFormatException: For input string: "1one"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at k.main(k.java:3)
If I wanted to allow both , and . and not just the decimal point specified by the locale, I would replace any , and . with the locale specified decmial point.
Using a simple regex, you can check if it contains any non numerical characters like so:
String input = "1one2";
String numerical = input.replaceAll("[^0-9.]", "");
if (input.equals(numerical)) // If you remove all non numbers, still the same string
After which you can parse it for a double.
Hello Im new to programming
and as title I was wonder how you can find last digit of any given number?
for example when entering in 5.51123123 it will display 3
All I know is I should use charAt
Should I use while loop?
thanks in advance
You would want to do something like this:
double number = 5.51123123;
String numString = number + "";
System.out.println(numString.charAt(numString.length()-1));
When you do the number + "", Java "coerces" the type of number from a double to a string and allows you to perform string functions on it.
The numString.length()-1 is because numString.length() returns the count of all the characters in the string BUT charAt() indexes into the string and its indexing begins at 0, so you need to do the -1 or you'll get a StringIndexOutOfBoundsException.
You can use below function simply and you can customize data types accordingly,
private int getLastDigit(double val){
String tmp = String.valueOf(val);
return Integer.parseInt(tmp.substring(tmp.length()-1));
}
You can't use charAt on a floating point variable (or any other data type other than Strings). (Unless you define a charAt method for your own classes...)
You can, however, convert that floating point number to a string and check the charAt(str.length()-1).
Convert your float variable to string and use charAt(strVar.length - 1).
double a=5.51123123;
String strVar=String.valueOf(a);
System.out.print(strVar.charAt(strVar.length -1);
Double doubleNo = 5.51123123;
String stringNo = doubleNo.toString();
System.out.println(stringNo.charAt(stringNo.length()-1));
Let's say I have a time hh:mm (eg. 11:22) and I want to use a string tokenizer to split. However, after it's split I am able to get for example: 11 and next line 22. But how do I assign 11 to a variable name "hour" and another variable name "min"?
Also another question. How do I round up a number? Even if it's 2.1 I want it to round up to 3?
Have a look at Split a string using String.split()
Spmething like
String s[] = "11:22".split(":");;
String s1 = s[0];
String s2 = s[1];
And ceil for rounding up
Find ceiling value of a number using Math.ceil
Rounding a number up isn't too hard. First you need to determine whether it's a whole number or not, by comparing it cast as both an int and a double. If they don't match, the number is not whole, so you can add 1 to the int value to round it up.
// num is type double, but will work with floats too
if ((int)num != (double)num) {
int roundedNum = (int)num + 1;
}