Pact-js: Floating points are incorrectly converted to integers

Created on 31 Jul 2017  路  3Comments  路  Source: pact-foundation/pact-js

From: https://gitter.im/realestate-com-au/pact?at=597b7cacc101bc4e3acbda60

I have my consumer pact saving a json node as float like "score": 1.0,
however the pact (json file) is saving it as "score": 1, (int)
my provider service (Java) returns a float and the matcher fails:

java.lang.AssertionError: 
0 - $.facts.0.score -> [{mismatch=Expected 1 but received 1.0, diff=}]
why pact-js is overriding 1.0 to 1 to the pact file
Awaiting feedback Triage

Most helpful comment

And this is what happens when you create a language in 10 days.

All 3 comments

OK, so I think the problem is this. All number types in JS are stored as "number" and the underlying representation is a float (i.e. calling typeof on 1.0 and 1 and 1.000000000000000000001 always yields "number").

The problem is, it seems to automatically round to the nearest integer if the decimal precision doesn't add any extra information value (i.e. 1.000000 gives us no more information than simply 1). Here is a simple way of testing this:

screenshot

As you can see, 1.0 is immediately represented as the integer 1 (but under the hood it is stored as a float, I believe). So the solution here?

"score": 1.01

If you needed _really_ high precision, I'd suggest using something like the bignumber library, encoding it as a string, and using a matcher like follows to ensure the precision you require:

term({
  matcher: "[0-9]+\.[0-9]{8,}",
  generate: "1.00000183"
})

And this is what happens when you create a language in 10 days.

Closing issue - we have our answer.

Was this page helpful?
0 / 5 - 0 ratings