Java Integer.parseInt() Not Working for Large Numbers - java

I have the following simple piece of code which is intended to detect that a given IPv4 address indeed only has numeric values (that is after the dots have been stripped):
import edu.gcc.processing.exceptions.net.IPAddressNumericException;
//Get the IP address
String address = "239.255.255.255";
//Check to see if this is a number
try {
String IPNumbers = address.replace(".", "");
Integer.parseInt(IPNumbers);
} catch (NumberFormatException e) {
System.out.print(e.getMessage());
}
For some reason, the NumberFormatException is fired, and I get this error:
For input string: "239255255255"
Could someone please help me understand this? The parseInt() method works on smaller numbers, such as 127001.
Thank you for your time.

try using Long.parseLong(IPNumbers)

Why not use a regular expression, or break it down into its components by using split(".")?
There are other limitations besides needing to consist solely of digits. For example:
666.666.666.666
This will parse just fine, but is an... unlikely IP.
Breaking it up into its parts lets you determine (a) that it has four parts, and (b) that each part actually makes sense in the context of an IP address.
You could also use an InetAddress implementation, or InetAddressValidator from Apache Commons.

For very large integers you may want to use the BigInteger class (or BigDecimal), as the values may exceed the limits of Integer.
Integer Limits:
Minimum : -2147483648
Maximum : 2147483647
Using BigInteger:
string s = "239255255255";
BigInteger yourNumber = new BigInteger(s);

239255255255 is too big to be held by an Integer. Try using a BigInteger or a BigDecimal.

Range of an Integer is -2,147,483,648 to 2,147,483,647, the number you have above mentioned is not included in these range, so use long , the range of long primitive type is in between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
So for your case its better to use Long.parseLong() function to convert such large number to long type.

The logical step up from an integer is a long

Related

How to convert string to number in java ? But i am not looking for hashCode as it wont give unique number. at least i want math logic for same

Hi I want to convert string to some unique number in java.
Exmple: "Production-0-1" to 100021
"Process-23-30" to 12310
And all return number has to be unique.
I dont wanted to use hashCode as they can return duplicate like "Aa" and "BB" has same has code.
Let me know math logic to create this is no method available.
String random = "Production-0-1";
String bi = new BigInteger(random.getBytes("UTF-8")).toString();
BigInteger numBig = new BigInteger(bi);
System.out.println(numBig);
Based on #markspace comments, I tried the following and every time it produces random unique number but beware if you have a very large String and a limited memory space then the output may go out of bound.

Disable Java making big number smaller? (10,000,000,000 to 1E10)

I have a big number in a database; in this case, 10,000,000,000. Whenever I use that information for something, like sending a message with it, instead of 10,000,000,000, it says 1E10, and I really do not want that.
Can I avoid that in any way?
If I go to the database, the value is 10,000,000,000.
It's the same number, just represented in scientific notation.
Since you don't describe how you are storing the value, you can use DecimalFormat#getNumberInstance to help format it to one that doesn't contain the scientific notation.
double foo = 10000000000L;
System.out.println(foo);
System.out.println(DecimalFormat.getIntegerInstance().format(foo));
This outputs:
1.0E10
10,000,000,000

how to printf a long typed value using input size modifier?

This is basically what I am trying to do
// ... some code, calculations, what have you ...
long timeToAdd = returnTimeToAddInLongFormat();
// lets output the long type now, and yes i need the width and precision.
System.out.printf("Time to add: %13.10ld", timeToAdd);
I've read most of the google searches around the topic and think I understand how to do it conceptually, but the JRE keeps throwing me a UnknownFormatConversionException and telling me my input size modifier l doesnt work.
Is there another way to do this, or did I miss something small?
Java treats all integer values as d, there is no ld. Even byte and BigInteger is a d type. It also assumes integers have no decimal places. If you want to show 10 zeros, you can convert to double first and use f

Java long to binary

something I thought was simple ends up not so much.
I need to convert a long number to binary.
For example:
String b = Integer.toBinaryString(1028);
the output is 10000000100
but when I use Integer.toBinaryString(2199023255552); it does not work. Of course the number is too big for this function and I can't find one that does convert from long.
Any suggestions?
Thank you.
Add an L to indicate its a long<1> and use the Long class<2>:
Long.toBinaryString(2199023255552L);
<1> Constants in java are considered ints unless you specify otherwise.
<2> Integer.toBinaryString() receives an int as parameter, not long.

Java: (int)(float)Float.valueOf(s) or Float.valueOf(s).toInt()

I just bumped into this little problem and I wanted the input of other people on this
I was wandering what was the best solution to convert a String to an int
(int)(float)Float.valueOf(s)
or
Float.valueOf(s).toInt()
s is a String inputed from a textfield so I can not guarantee that it is necessarily an int
my instincts is that the double cast is ugly and should be avoided
Your input?
Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.
If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).
If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)
If you want to round to the nearest int, use Math.round() instead of a cast.
You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
that shouldn't be a concern for your use-case, and
the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.
You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).
Integer.parseInt(string) would be best
int x = Integer.parseInt(s);
Would be best to check if the string is an int before calling this.
As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex
^[0-9]*$
which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use
Integer.parseInt(String s) throws NumberFormatException

Categories

Resources