Long.parseLong giving NumberFormatException - java

My issue is that
checksum = Long.parseLong("-986.9");
is giving NumberFormatException.
Isn't this a parsible long?

A Long is not a decimal. Use Double and convert :
Double.parseDouble("-986.9").longValue();

No it isn't. A long is a numeric integer type, and your number has a decimal point.
You want a double here (ie Double.parseDouble()).

long is an integer data type, -986.9 is not an integer. The below works for me.
long checksum = Long.parseLong("-986");
System.out.println(checksum);
double checksum2 = Double.parseDouble("-986.6");
System.out.println(checksum2);

Use a double, use the method Double.parseDouble(var)

Related

Casting Double object to int

How can I convert from a Double object to an int? The following code works but seems slightly unconventional (with casting twice):
Double d = new Double(4.0);
int i = (int)(double)d;
When I try int i = (int)d, I get an error from Eclipse (Cannot cast from Double to int), which makes sense. Nevertheless, is there a simpler way of converting a Double object to an int?
Double.intValue()
is the provided method that does that conversion.
If you cast double to int you will loss decimal value.. so 4.99 double become 4 int. If still want to convert than try-
int i = d.intValue();
In your case you use
Double.intValue()
as a method to convert the Double Object to Integer.

Changing a String decimal (2.9) to Int or Long issues

Okay, I'm fairly new to java but I'm learning quickly(hopefully). So anyway here is my problem:
I have a string(For example we will use 2.9), I need to change this to either int or long or something similar that I can use to compare to another number.
As far as I know int doesn't support decimals, I'm not sure if long does either? If not I need to know what does support decimals.
This is the error: java.lang.NumberFormatException: For input string: "2.9" with both Interger.parseInt and Long.parseLong
So any help would be appreciated!
You can't directly get int (or) long from decimal point value.
One approach is:
First get a double value and then get int (or) long.
Example:
int temp = Double.valueOf("20.2").intValue();
System.out.println(temp);
output:
20
int and long are both integer datatypes, 32-bit and 64-bit respectively. You can use float or double to represent floating point numbers.
That string (2.9) is neither integer nor long. You should use some decimal point types, for example float or double.
Both int and long are integer values (being long the representation of a long integer that is an integer with a higher capacity). The parsing fails because those types do not support a decimal part.
If you were to use them and enforce a casting you're relinquishing the decimal part of the number.
double iAmADouble = 100 / 3;
int iWasADouble = (int)iAmADouble; //This number turns out to be 33
Use double or float instead.

Convert String (representing decimal number) to long

I've googled around a bit but could not find examples to find a solution. Here is my problem:
String s = "100.000";
long l = Long.parseLong(s);
The 2nd line of code which tries to parse the string 's' into a long throws a NumberFormatException.
Is there a way around this? the problem is the string representing the decimal number is actually time in milliseconds so I cannot cast it to int because I lose precision.
You could use a BigDecimal to handle the double parsing (without the risk of precision loss that you might get with Double.parseDouble()):
BigDecimal bd = new BigDecimal(s);
long value = bd.longValue();
as i don't know is your 100.000 equals 100 or 100 000
i think safest solution which i can recommend you will be:
NumberFormat nf = NumberFormat.getInstance();
Number number = nf.parse("100.000");
long l = number.longValue();
'long' is an integer type, so the String parse is rejected due to the decimal point. Selecting a more appropriate type may help, such as a double.
Just remove all spaceholders for the thousands, the dot...
s.replaceAll(".","");
You should use NumberFormat to parse the values
We can use regular expression to trim out the decimal part. Then use parseLong
Long.parseLong( data.replaceAll("\..*", ""));
If you don't want to loose presision then you should use multiplication
BigDecimal bigDecimal = new BigDecimal("100.111");
long l = (long) (bigDecimal.doubleValue() * 1000);<--Multiply by 1000 as it
is miliseconds
System.out.println(l);
Output:
100111

Converting a String that contains decimal to Long

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

How to convert Float(Wrapper class) to Integer wrapper class?

how to convert Float to Integer in java?
Float value = 30.0F
how to convert above value to Integer?
Please help me?
Use Float.intValue():
Integer i = value.intValue();
Note that this causes autoboxing, but since you're planning to create an Integer anyway, this won't have any performance impact.
Note also that you should pay attention to rounding: intValue() and an int cast round toward zero. For rounding to the nearest integer, use Math.round(), for rounding down use Math.floor(), for rounding up use Math.ceil(). If you need some other kind of rounding, you need to implement it yourself.
Try this:
Float f = new Float(10.5);
Integer i = new Integer((int)Math.ceil(f));
f.intValue() is the way to go..
new Float(value).intValue() or simly cast it to int int v = (int) value
You can just do this:
Float value = 30.0f;
Integer intVal = value.intValue(); // auto-boxing happens here
Use value.intValue() method.
Float value = 30.0F;
Integer intValue=Integer.valueOf(value.intValue());

Categories

Resources