Michael Durrant
Michael Durrant

Reputation: 96584

How to have a Mocha test with 2 decimal places in Javascript - Big and Decimal both giving issues

I tried using the Big library but including that code just gives me an error

Error: Cannot find module 'tap' 
...

So I tried to use Decimal instead. I did

npm install Decimal

And then added

const Decimal = require('decimal');

I followed the examples but I just get { Object (internal, as_int, ...) } as my comparison when I use

const amount = 25.12
let expectedMoney;
const Decimal = require('decimal');
...
expectedMoney = new Decimal(amount * 1.1)
expect(27.63).to.equal(expectedMoney);

Error:

 AssertionError: expected 27.63 to equal { Object (internal, as_int, ...) }
  at Context.<anonymous> (index.test.js:19:22)

I also tried:

expect(27.63).to.equal(expectedMoney.as_int.value);

But that gives

expected 27.63 to equal 27632000000000004

And I tried

expect(27.63).to.equal(expectedMoney.toFixed(5));

But that gives

TypeError: expectedMoney.toFixed is not a function

Upvotes: 0

Views: 1110

Answers (1)

J.F.
J.F.

Reputation: 15225

You don't need any library if you only want to compare with a simple "double" number.
What I used to do is cut the number at two decimal values in two ways.

I use a mathematical way using a the precision I want to get and substracting the values in this way:

var precision = 0.01;
expect(Math.abs(27.63 - expectedMoney) <= precision).to.equal(true);

The numbers will be the same if the are different in 0.001 or more. So, for example: 1.00 will be the same as 1.001 but different with 1.01.

Example here:

var precision = 0.01
//Works using 1 or 1.00
console.log(Math.abs(1 - 1.001) <= precision)
console.log(Math.abs(1 - 1.01) <= precision)

The other way is simply using toFixed() and parseFloat because toFixed returns a string.

const amount = 25.12
var expectedMoney = parseFloat((amount* 1.1).toFixed(2))
expect(27.63).to.equal(expectedMoney);

Example:

const amount = 25.12
var expectedMoney = parseFloat((amount* 1.1).toFixed(2))
console.log(27.63 == expectedMoney)

Upvotes: 3

Related Questions