Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String that contains decimal to Long

Tags:

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 ?

like image 202
Pit Digger Avatar asked Oct 04 '12 17:10

Pit Digger


People also ask

How do you convert a decimal to a long String?

You CAN convert any number to String with, for instance, Long. toString(long l) .

Can we store decimal value in long?

Long variables can hold numbers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Operations with Long are slightly slower than with Integer . If you need even larger values, you can use the Decimal Data Type.

Can Java long contain decimals?

Values of type long that exceed the range of int can be created from long literals. Integer literals can be expressed by these number systems: Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day.


3 Answers

The value 30000.1 is an invalid long value. You could parse the double value first:

lDurationMillis = (long)Double.parseDouble("30000.1");
like image 118
Reimeus Avatar answered Oct 13 '22 12:10

Reimeus


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);
like image 27
Gijs Overvliet Avatar answered Oct 13 '22 11:10

Gijs Overvliet


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.

like image 25
Miserable Variable Avatar answered Oct 13 '22 10:10

Miserable Variable