I have to convert a String "1392298553937999872" into an int. The string is a timestamp. Normally this should be possible to convert it into a int by using:
Integer i = Integer.valueOf(1392298553937999872);
But I receive the following exception:
java.lang.NumberFormatException: For input string:
"1392298553937999872"
If I use double it works, but the number is wrong. So how can I convert a timestamp into an int?
convert the string to long.
String a="1392298553937999872";
long b= Long.parseLong(a);
The number is greater than the max value of Integer use Long
Long l = new Long("1392298553937999872");
The number you're trying to convert exceeds the Integer.MAX_VALUE value. You'd better use BigInteger.
BigInteger bigInteger = new BigInteger("1392298553937999872");
The value you're trying to convert is greater than the Integer.MAX_VALUE (2,147,483,647), you should use one of the alternative types Long, BigInteger:
Long bigValue = Long.parseLong("1392298553937999872");
// ...
Long bigValue = new Long("1392298553937999872");
// ..
Long bigValue = Long.valueOf("1392298553937999872");
// ...
BigInteger bigValue = new BigInteger("1392298553937999872");
If adding an additional library and the values might vary, you can also use apache commons' NumberUtils. The method NumberUtils.createNumber(String) will adapt based on the provided input:
Number bigValue = NumberUtils.createNumber(inputString);
Related
The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10
I want to convert binary string to dec.
public class HelloWorld{
public static void main(String []args){
System.out.println(Integer.parseInt("000011011111110111000001110000111110", 2));
}
}
I get error:
java.lang.NumberFormatException: For input string: "000011011111110111000001110000111110".
How to fix it?
Short solution - Integers simply don't go that high. That's not an int.
ParseInt() documentation mentions, you recieve a string and a radix, and get back the result of the convertion. However, integers are 4 bytes = 32 bits, and thus range from -(2^31) to 2^31-1, and your number - 11011111110111000001110000111110, is in fact 32 bits long - which means, it's bigger than the maximal value. Thus, the function throws this NumberFormatException - this is not a valid value for an int.
If you'd like to fix it, I'd use a ByteBuffer, like described here:
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort(); // use with a bigInteger instead. you could use any of the bytebuffer functions described in the link :)
You can use BigInteger class and store the number as long:
BigInteger bigInt=new BigInteger("000011011111110111000001110000111110");
long a=bigInt.longValue();
The value you are going to store is too big for int and does not fall inside the range the type int can hold(-(2^31) to 2^31-1).So it throws NumberFormatException.long is a suitable option here.
You can use Long.parseLong for the string in your question, still you may find a limit in that also, so you have to implement different logic.
You can have a method that convert the binary string to integer.
public static long binaryToInteger(String binaryString) {
char[] chars = binaryString.toCharArray();
long resultInt = 0;
int placeHolder = 0;
for (int i=chars.length-1; i>=0; i--) {
if (chars[i]=='1') {
resultInt += Math.pow(2,placeHolder);
}
placeHolder++;
}
return resultInt;
}
I am trying to convert "0x6042607b1ba01d8dl" into a long.
I have tried:
long value = new BigInteger("0x6042607b1ba01d8dl", 16).longValue();
long value = new BigInteger("0x6042607b1ba01d8dl", 32).longValue();
long value = Long.decode("0x6042607b1ba01d8dl");
Long.parseLong("0x6042607b1ba01d8dl");
Note: The Hex number "0x6042607b1ba01d8dl" has 17 numbers
From the javadoc for the BigInteger(String,int) constructor:
The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix.
So you just need to remove the 0x from your string:
long value = new BigInteger("6042607b1ba01d8d", 16).longValue();
The BigInteger constructor does not understand your 0x prefix.
Use e.g.
long value = new BigInteger("6042607b1ba01d8d", 16).longValue();
Or:
String number = "0x6042607b1ba01d8d";
long value = new BigInteger(number.subString(2), 16).longValue();
You can also use Long.decode(), which does accept a 0x prefix for decoding hex.
You can try this:
long value = Long.parseLong("6042607b1ba01d8d", 16);
Long.parseLong can sometimes fail for unsigned longs, so, the BigInteger approaches are better.
As said by the above answers in code form:
String bigHexNumber = "0x6042607b1ba01d8d";
if(bigHexNumber.subString(0, 1).equals("0x") {
bigHexNumber = bigHexNumber.subString(2);
}
long hexInLongForm = new BigInteger(bigHexNumber, 16).longValue();
I have following sample (link to ideone).
long lDurationMillis = 0;
lDurationMillis = Long.parseLong("30000.1");
System.out.print("Play Duration:" + lDurationMillis);
It throws an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "30000.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at Main.main(Main.java:9)
But why it wont let me convert that number to a string directly ?I can convert number to integer and than convert to double . But is there any other way ?
The value 30000.1 is an invalid long value. You could parse the double value first:
lDurationMillis = (long)Double.parseDouble("30000.1");
You could use BigDecimal in this case:
BigDecimal bd = new BigDecimal("30000.1");
long l = bd.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
System.out.println(l);
The title says converting string to long, first question is about coverting number to string, next statement about converting number to integer to string. I am confuse.
But for anything to do with floating points, I have to point you at obligatory reference What Every Computer Scientist Should Know About Floating-Point Arithmetic .
In java, int and long do not have fractional parts, so a string like 3000.1 cannot be covnerted to one of these. It can be converted to float or double but if you read the above article you will realize that the coversion can be lossy, i.e. if you canvert that double back to a String you may not get the original 3000.1 back. It will be something close, for appropriate defintion of close, but may not be same.
If you want to use exact precision then BigDecimal is your friend. It will be much slower then the number types, but it will be precise.
Because long can't have fractional part, you could convert it to double and then cast it to long ignoring fractional part
You can do NumberFormat handling as below :
long lDurationMillis = 0;
try{
NumberFormat nf = NumberFormat.getInstance();
lDurationMillis = nf.parse("30000.1").longValue();
System.out.print("Play Duration:" + lDurationMillis);
}catch(ParseException e)
{
e.printStackTrace();
}
Output:
Play Duration:30000
The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10