Title: Compare Two Floats
Slug: compare_two_floats
Summary: Compare Two Floats Using Scala.
Date: 2017-01-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon
This tutorial was inspired by the awesome Scala Cookbook.
In [15]:
// Create a value
val price_old = 2.343232
// Create a value that is very slight different
val price_new = 2.343231
In [16]:
// Define a function called ~= that contains three arguments: two numbers and a precision level,
def ~=(x: Double, y: Double, precision: Double) = {
// If the absolute difference is less than the precision level, return true, otherwise return false
if ((x - y).abs < precision) true else false
}
In [21]:
// Compare price_old and price_new with 0.000001 precision
~=(price_old, price_new, 0.000001)
Out[21]:
In [23]:
// Compare price_old and price_new with 0.1 precision
~=(price_old, price_new, 0.1)
Out[23]: