I'm trying to convert a String(32 digits) into a long and it returns a NumberFormatException. I've tried it with Long.parseLong() and a Long object, but bone of them worked.
code:
class ConvertStringToLong{
public static void main(String in){
long out;
out=java.lang.Long.parseLong(in);
System.out.println(out);
}
}
i also tried
class ConvertStringToLong{
public static void main(String in){
long out;
out = new Long(in);
System.out.println(out);
}
}
The long datatype is a 64-bit signed integer, so its maximum value is 2^63 - 1, which is 19 digits long. To represent larger numbers than this, you will need to use a different datatype, such as BigInteger, which allows arbitrarily large numbers. The constructor new BigInteger(String val) will parse a string as a BigInteger.
Documentation here (https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html) says that:
BigInteger must support values in the range -2^Integer.MAX_VALUE
(exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values
outside of that range. The range of probable prime values is limited
and may be less than the full supported positive range of BigInteger.
The range must be at least 1 to 2^500000000.
You can favor using a BigInteger object.
Related
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.
Because:
The int data type is a 32-bit signed two's complement integer. It has
a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
Code Throwing the NumberFormatException:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?
Use BigInteger to avoid numeric limits of primitive int and long:
BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16); // Radix 16 indicates hex
System.out.println(x16);
The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.
Demo.
If your input value can be arbitrarily large, then #dasblinkenlight's answer involving BigInteger is your best bet.
However, if your value is less than 263, then you can just use Long instead of Integer:
String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex); // 2540be3ff
Live demo.
Use Integer.parseUnsignedInt
When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:
int n = Integer.parseUnsignedInt("CAFEBABE", 16);
(I used hexadecimal here, as it is easier to see that above we are just in that range.)
However 9_999_999_999 is above the unsigned int range too.
Try this way:
String largeNumberAsAString = "9999999999";
System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));
I'm struggling to figure out what the compile/syntax error is in my code.
public class CreditCardValidation {
public static void main (String[] args){
System.out.print(prefixMatched(4388576018402626, 4388));
}
/*
Return the number of digits in d
*/
public static int getSize(long d) {
int size = 0 ;
while( d > 0 ) {
d = d / 10 ;
size = size + 1 ;
}
return size ;
}
/*
Return the first k number of digits from number. If the number of digits in number is
less than k, return the number.
*/
public static long getPrefix(long n, int k) {
int f = getSize(n)-k;
long prefix = n/((int)(Math.pow(10, f)));
return prefix;
}
/*
Return true if the digit d is a prefix for number.
*/
public static boolean prefixMatched( long number, int d ) {
if ( d == getPrefix(number, 4))
return true ;
else
return false ;
}
}
As you can see I'm trying to call prefixMatched to check whether the credit card number meets the requiremen; if digit d is a prefix for number. However, the only thing I get back from the compiler is:
"CreditCardValidation.java:6: integer number too large: 4388576018402626
System.out.print(prefixMatched(4388576018402626, 4388));
^"
I'm sorry if my question is too vauge, this is my first post.
You need to indicate to the compiler that your constant (the CC number) is a long. Put an L on the end of the constant.
It's actually a little easier to treat CC numbers as strings and use charAt(x) to calculate check digits.
The problem is that you are specifying an integer literal 4388576018402626 and that number is larger than the maximum integer, 2147483647.
You are attempting to pass it to a method that takes a long, so make it a long literal by appending L:
System.out.print(prefixMatched(4388576018402626L, 4388));
The JLS specifies this behavior in Section 3.10.1:
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
and
It is a compile-time error if a decimal literal of type int is larger than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator (§15.15.4).
add L at the end of your literal :
4388576018402626L
You should use Long instead of Integer
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The unsigned long has a minimum value of 0 and maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
You should use following to avoid exception:
System.out.print(prefixMatched(4388576018402626L, 4388));
The L indicates given value is long. You can use either l or L but I prefer to use L because it looks goods while looking code.
Source: Oracle Docs.
For this code, I would recommend using String instead of dealing with long and int. It's far easier when trying to match the first four digits, which can be isolated easily using String#substring: (String_name).substring(0,4) will be return first four digits of the String. This can then be parsed as an int using Integer#parseInt, or simply compared to another String (if the prefix were a String as well).
I am creating a bank account.which has a 'accnum' as variable.which has integer value with size of 12 bytes.
let say the bank account number is 180020131111.How do you initialize to a variable?
public class number{
public static void main(String[] args){
private long x=180020131111; // is not working..
System.out.println(x);
}
}
180020131111 is an integer literal, which cannot fit into an int type. You should append an L at the end to make it long literal.
private long x = 180020131111L;
Well, I would rather store account number as String. I don't think there is really any need for storing it as numeral, as you are just going to display it. I mean it would really look weird if you are going to do some arithmetic operations on account numbers.
By default Integral Literals are treated as 32 bit int and not 64 bit long in java..
Use this
private long x=180020131111L;
The character l ot L at the end makes integral literals long
The largest Java primitive integral type is long which is a 64 bit (8 byte) signed type. If you want to represent numbers larger that 263 - 1 == 9,223,372,036,854,775,807, you need to use BigInteger or BigDecimal.
The problem with this statement ...
private long x=180020131111;
... is that you are using the syntax for an int literal. A long literal requires a l or L suffix. (FWIW - this number does not require 9 bytes to represent ...)
I'm trying to use BigInteger values along side Math.Log10 method.
final BigInteger answerNo = fact;
final int digits = 1 + (int)Math.floor(Math.log10(answerNo));
Unfortunately the compiler says incompatible types.
If I change the ints to BigIntegers it still doesn't like it.
Instead of doing a log10 you can find the number of digits by simply doing:
int digits = answerNo.toString().length();
You can't assign an int to a BigInteger - you could write: final BigInteger answerNo = BigInteger.valueOf(fact);
Mat.log10 expects a double, not a BigInteger
If you don't mind a loss of precision, you could simply use doubles:
final int digits = 1 + (int)Math.floor(Math.log10(fact));
If you care about precision, you will need to calculate the log manually.
BigInteger.toString() can be inefficient in terms of memory if you only care for count of digits.
You can instead try converting BigInteger into a BigDecimal and use the BigDecimal.precision() to achieve the same. See this answer for details.
Which Java data type would be able to store a big numerical value, like 9999999999?
Your concrete example could be stored in long (or java.lang.Long if this is necessary).
If at any point you need bigger numbers, you can try
java.math.BigInteger (if integer), or java.math.BigDecimal (if decimal)
In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:
long l1 = 9999999999; // this won't compile
long l2 = 9999999999L; // this will work
You can store this in a long. A long can store a value from -9223372036854775808 to 9223372036854775807.
A primitive long or its java.lang.Long wrapper can also store ten digits.
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
you can use long or double.
You could store by creating an object that hold a string value number to store in an array list.
by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");
objt is created by the constructor of BigInt class. Inside the class look like.
BigInt{
ArrayList<Integer> myNumber = new ArrayList <Integer>();
public BigInt(){}
public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }
}
A wrapper class java.lang.Long can store 10 digit easily.
Long phoneNumber = 1234567890;
It can store more than that also.
Documentation:
public final class Long extends Number implements Comparable<Long> {
/**
* A constant holding the minimum value a {#code long} can
* have, -2<sup>63</sup>.
*/
#Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* A constant holding the maximum value a {#code long} can
* have, 2<sup>63</sup>-1.
*/
#Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}
This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.
If you want to take user input then you should take that as string, then convert that into long.
//Take user input using Scanner class
Scanner sc = new Scanner(System.in);
String str = sc.next();
//Convert that to long
long num = Long.parseLong(str);
System.out.println(num); // This is not a string anymore