long

How to handle very large numbers in Scala (BigInt, BigDecimal)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.6, “Handling Very Large Numbers in Scala.”

Problem

You’re writing a Scala application and need to use very large integer or decimal numbers.

Solution

Use the Scala BigInt and BigDecimal classes. You can create a BigInt:

Scala: How to parse a number from a String

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

Problem

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

How to convert between numeric types in Scala

Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?

Solution

Instead of using the “cast” approach in Java, use the to* methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):

Scala: How to parse a number from a String

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 data types: bit sizes, ranges, and docs

Scala FAQ: What are the Scala data types? How many bits do they use to store their data, and what is the range of those data types?

Courtesy of the excellent book, Programming in Scala, here is a list and description of the Scala data types, including bit sizes and data ranges:

PHP here document (heredoc) examples

PHP here doc FAQ: Can you share some examples of the PHP "here" doc (heredoc) syntax?

"Here" documents in many languages are provided as a way to address the following problems:

How to convert Strings to numbers (int, float, etc.)

Java String to number FAQ: How do I convert a String to a number in Java?

You convert a Java String to a number using the methods of the class whose type you want to convert to. For instance, if you want to try to convert a String to an int, you use the parseInt() method of the Java Integer class, like this: 

How do I convert a String to a long with Java?

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

Answer: The Long class includes a method named parseLong() that serves just this purpose. An example of a simple program that performs this conversion is shown below:

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.