1

It is observed that the multiplication of two numbers in karate feature file is getting evaluated incorrectly

when i try the below multiplication

* print  38.30 * 1.05

I am getting 40.214999999999996

I would expect the result to be 40.215

Is there any setting I need to do or is there any solution to this problem? Kindly advise.

Sourabh Roy
  • 159
  • 1
  • 18

1 Answers1

1

Karate uses JS behind the scenes, and this is a known problem with JS. Teams also typically don't do math in Karate and it is not designed for that.

That said, you will get the results you want by using the Java BigDecimal class.

* def BD = Java.type('java.math.BigDecimal')
* def a = new BD('38.30')
* def b = new BD('1.05')
* def result = a.multiply(b)
* match result == 40.215

I leave it as an exercise to you to write a helper utility that will make this easier. Finally also refer to the docs on other cases where you may need to force the use of a BigDecimal: https://github.com/karatelabs/karate#large-numbers

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    Thank you @Peter Thomas for the workaround. However I could not completely follow when you say that teams don't do math in karate. Suppose I have an api to calculate distance and accepted inputs are speed and time. How can I write the tests that distance is coming correctly for different data sets? – Sourabh Roy May 17 '23 at 18:47
  • 1
    @SourabhRoy I said "typically". you are welcome to do what is right for your use-case, and I recommend that tests be less "clever" and more direct and deterministic: https://stackoverflow.com/a/54126724/143475 – Peter Thomas May 17 '23 at 19:05