# number

## How to compare floating-point numbers in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.5, “Comparing Floating-Point Numbers in Scala.”

## Problem

You need to compare two floating-point numbers in Scala, but as in some other programming languages, two floating-point numbers that should be equivalent may not be.

## How to format numbers and currency in Scala

Scala FAQ: How can I format numbers and currency in Scala, such as to control the number of decimal places and commas in the values, typically for printed output.

## Basic formatting

For basic number formatting, use the `f` string interpolator shown in Recipe 1.4 of the Scala Cookbook, “Substituting Variables into Strings”:

```scala> val pi = scala.math.Pi
pi: Double = 3.141592653589793

scala> println(f"\$pi%1.5f")
3.14159```

A few more examples demonstrate the technique:

## How to use BigInt and BigDecimal when you need very large numbers in Scala

Scala FAQ: I’m writing an application and I need to use very large integer or decimal (floating-point) numbers; what’s the best approach?

## Solution

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

```scala> var b = BigInt(1234567890)
b: scala.math.BigInt = 1234567890```

or a `BigDecimal`:

## 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):