tolerance

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 compare floating-point numbers in Scala

Scala FAQ: I 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 do I comparison floating-point numbers?

Solution

As in Java and many other languages, you solve this problem by creating a method that lets you specify the precision for your comparison. The following Scala “approximately equals” method demonstrates the approach: