I'm trying to round a String value using Math.round as so:
String numberString = "61867345124";
int value = Math.round(Float.parseFloat(numberString));
but I'm getting value = 2147483647, what is going on here?
Actually, you have two issues here,
First, the output is 2147483647 because that is the max value an integer can store in Java. And your number is larger than that. You can confirm the max value for a primitive type by calling MAX_VALUE against its wrapper class, like below,
System.out.println(Integer.MAX_VALUE);
If the return value of Math.round is larger than Integer.MAX_VALUE it will return an integer having maximum value it can store,
From the documentation here,
If the argument is positive infinity or any value greater than or
equal to the value of Integer.MAX_VALUE, the result is equal to the
value of Integer.MAX_VALUE.
To resolve that you can store the result in a long typed variable.
Second, that will still not get you desired results because Math.round if provided with a float input will return an integer. You need it to return a long instead which is returned if you provide it a double value.
Here are the definitions, from the documentation of Math class.
static int round(float a)
static long round(double a)
To sum up you need to both store the output as a long as well as you need to parse the string value as double, like below,
String numberString = "61867345124";
long value = Math.round(Double.parseDouble(numberString));
System.out.println(value);
Looks like you are using a number way larger than an integer can contain, so the output is defaulting to the maximum integer value of 2147483647. You probably want to use a long to store that value.
Related
why I am getting error integer too large. As I declare it as long.
Here is my code
Scanner sc = new Scanner(System.in);
long x=sc.nextLong();
if(x>=-9223372036854775807 && x<=9223372036854775806)
System.out.println("long");
Put an "L" at the end of your numbers:
if(x>=-9223372036854775807L && x<=9223372036854775806L) System.out.println("long");
Such that the compiler sees them as longs, not ints.
By default all constant numbers all int, so you need to put L at the end of your numbers: 9223372036854775806L
But, the better way is using Long.MAX_VALUE and Long.MIN_VALUE instead of hard coding those large numbers.
You are not getting this error because of your x variable you are getting it because of number literals -9223372036854775807 and 9223372036854775806.
Because by default number literals are treated as int and you need to append an extra L at end of them to tell compiler to treat them as long literal.
How ever you should use Long.MAX_VALUE and Long.MIN_VALUE constants for this comparison. If your max and min value varies from the Long.MIN_VALUE and Long.MAX_VALUE, it is a best practice to create constants for them and then use them e.g.
final static long MIN_VALUE = 100000L;
final static long MAX_VALUE = 10000000L;
if(x<MIN_VALUE && x>MAX_VALUE) System.out.println("This is an invalid value");
I'm initializing two integers a and b.
It compiles fine for a but there is an error for b.
public class Main_1 {
public static void main(String[] args) {
int a = -2147483648; //Working fine
int b = -(2147483648); //Compilation error: The literal 2147483648 of type int is out of range
}
}
Please help me understand this behavior ?
The reason is that the int datatype has valid values in the range [-2147483648, 2147483647].
When you wrap 2147483648 inside parentheses, it becomes an expression that will be evaluated as an int. However, 2147483648 is too big to fit in an int (too big by one).
The problem does not happen for -2147483648 because it is a valid int value.
Relevant parts of the JLS:
adding parentheses creates a "Parenthesized Expressions" (section 15.8.5)
an integer literal, such as 2147483648, is treated as an int by default (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).
int values go from -2147483648 to 2147483647. So -(2147483648) is OutOfRange because the value inside the brackets is evaluated as an int. The max value you can put into the brackets is
Integer.MAX_VALUE //Which is equals to 2147483647
The compilation error is pretty clear: you are using the int literal which is out of range. If you really want to do it, you may use long literal:
int b = (int) -(2147483648L);
Or double literal:
int b = (int) -(2147483648.0);
Max value of int is 2147483647 and min value of int is -2147483648. But when you put 2147483648 into braces it initially consider as +2147483648 and it is not in valid for int rage.
A good way to visualize this is to look at (int) -(2147483648) as:
(int) -1 * (2147483648)
When this is evaluated by the compiler, it says, I have to first convert the number in the parenthesis to an integer, then multiply that by negative 1. It then proceeds to do a range check on the number and discovers that it is larger than what can fit in an integer (2147483648), which is the compilation error.
int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
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).
Why does this code throw NumberFormatException?
int a = Integer.parseInt("1111111111111111111111111111111111111111");
How to get the value of int for that String?
The value that you're attempting to parse is much bigger than the biggest allowable int value (Integer.MAX_VALUE, or 2147483647), so a NumberFormatException is thrown. It is bigger than the biggest allowable long also (Long.MAX_VALUE, or 9223372036854775807L), so you'll need a BigInteger to store that value.
BigInteger veryBig = new BigInteger("1111111111111111111111111111111111111111");
From BigInteger Javadocs:
Immutable arbitrary-precision integers.
This is because the number string is pretty large for an int . Probably this requires a BigInteger .
There is no integer value for that string. That's why it's throwing an exception. The maximum value for an integer is 2147483647, and your value clearly exceeds that.
Here is the code I am working with in a main method:
String numbers = "12345678900";
long upc = Integer.parseInt(numbers);
System.out.println(upc);
gives me:
Exception in thread "main" java.lang.NumberFormatException: For input string: "12345678900"
at java.lang.NumberFormatException.forInputString...
at java.lang.Integer.parseInt....
at java.lang.Integer.parseInt...
at testRun.main...
I cannot use a double, they need to be stored as values without a decimal. I am trying to get the string of numbers from a string into a variable that holds numbers (no decimals)
To parse a long, use Long.parseLong, not Integer.parseInt. That way, you get access to the full range of long values (whereas with parseInt, you only get the rather more restricted range of int values).
Use Long.parseLong()
String numbers = "12345678900";
long upc = Long.parseLong(numbers);
System.out.println(upc);
use
String numbers = "12345678900";
long upc = Long.parseLong(numbers);
System.out.println(upc);
The number you are passing is outside the range of integer which is from -2,147,483,648 to 2,147,483,647.
Try using the static function parseLong
Your number is enough long to not fit in Integer. So, you can't cast in integer. You can cast it in Long by calling Long.parseLong(number).
Use
long upc = Long.parseLong(numbers);