temelm
temelm

Reputation: 788

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.

Upvotes: 2

Views: 13240

Answers (7)

jean joseph
jean joseph

Reputation: 82

We can use regular expression to trim out the decimal part. Then use parseLong

Long.parseLong( data.replaceAll("\..*", ""));

Upvotes: 0

psabbate
psabbate

Reputation: 777

You should use NumberFormat to parse the values

Upvotes: 0

user902383
user902383

Reputation: 8640

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();

Upvotes: 4

Amit Deshpande
Amit Deshpande

Reputation: 19185

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

Upvotes: -2

Kenogu Labz
Kenogu Labz

Reputation: 1134

'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.

Upvotes: 2

Thomas
Thomas

Reputation: 661

Just remove all spaceholders for the thousands, the dot...

s.replaceAll(".","");

Upvotes: 0

assylias
assylias

Reputation: 328608

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();

Upvotes: 4

Related Questions