numberformatexception

Scala - How to parse a number from a String alvin May 30, 2015 - 6:34pm

Scala FAQ: How do I parse a number (Int, Long, Float, etc.) from a String in Scala?

Solution

Use the to* methods that are available on a String (courtesy of the Scala StringLike trait):

Scala: How to convert a String to an Int (Integer)

Scala FAQ: How do I convert a String to Int in Scala?

Solution: Use 'toInt()'

If you need to convert a String to an Int in Scala, just use the toInt method, which is available on String objects, like this:

What is a Java NumberFormatException?

Java exception FAQ: What is a Java NumberFormatException?

Answer: A Java NumberFormatException usually occurs when you try to do something like convert a String to a numeric value, like an int, float, double, long, etc.

The best way to show a NumberFormatException is by example, so here’s an example where I intentionally write bad Java code to throw a NumberFormatException:

Java: How to convert strings to numbers

Question: How do I convert a String to an int or a float?

Short answer: You want to use the Integer.parseInt() or Float.parseFloat() methods.

Here's an example Java program that shows how to convert a String to either an int or a float:

How do I convert a String to a double with Java? alvin August 9, 2007 - 5:05pm

Question: How do I convert a String to a double with Java?

Answer: Converting a String to a double requires that you first convert the String to a Double object, then convert the Double object to a double data type (Double is an object, while double is a primitive data type).

Here's the source code for an example Java program that performs this conversion:

Java String to float conversion example alvin August 19, 2001 - 8:04pm

Java String to float FAQ: How do I convert a Java String to a Java float?

Answer: Here's an example that demonstrates how to convert a Java String to a float value. This example code segment converts the String "100.00" to a Java float: