Scala: How to parse a number from a String alvin July 10, 2017 - 1:25pm

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.1, “Parsing a Number from a String.”


You want to convert a String to one of Scala’s numeric types (Byte, Double, Int, Float, Long, Short).

What is a Java NumberFormatException? alvin November 29, 2007 - 5:37pm

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:

How to convert a Java String to an Int

Java String/int FAQ: How do I convert a String to an int data type in Java?

Answer: You convert a string to an integer using the parseInt method of the Java Integer class. The parseInt method converts the String to an int, and throws a NumberFormatException if the string can’t be converted to an int type.

Let’s take a look at two short examples.