Validate a number to have 2 decimal points

Hey All,

Wanted to know if we can create test to validate a certain number in response that has only 2 decimal place, if it has more than 2 decimal places then its a fail test.

e.g

“Details”: {
“rates”: [
{
“price”: 9.90
}

e.g something like

var jsondata = pm.response.json ();

pm.test(“Price has 2 decimal points”, function (){
pm.expect(jsondata.Details.rates[0].price).toFixed( 2 )

});

Your going to need a function to count the decimal places.

Something like.

// https://stackoverflow.com/questions/27082377/get-number-of-decimal-places-with-javascript

var countDecimals = function(value) {
  let text = value.toString()
  // verify if number 0.000005 is represented as "5e-6"
  if (text.indexOf('e-') > -1) {
    let [base, trail] = text.split('e-');
    let deg = parseInt(trail, 10);
    return deg;
  }
  // count decimals for number in representation like "0.123456"
  if (Math.floor(value) !== value) {
    return value.toString().split(".")[1].length || 0;
  }
  return 0;
}

let value1 = 37.435345;
let decimalPlaces1 = countDecimals(value1) //6

let value2 = 20.00; 
// note the 00 will be stripped into JavaScript, so the assertion is looking for less than 3 instead of eql 2.
let decimalPlaces2 = countDecimals(value2) //0

let value3 = 9.90; 
// the zero will also get stripped
let decimalPlaces3 = countDecimals(value3) //1

let value4 = "9.90"; 
// the function can take strings, so you could stringify the number when retrieving it.
let decimalPlaces4 = countDecimals(value4) // 2

let value5 = "9.901"; 
// boundary test
let decimalPlaces5 = countDecimals(value5) // 3

pm.test(`1: Two decimal places : ${value1}`, () => {
    pm.expect(decimalPlaces1).to.be.lessThan(3);
});

pm.test(`2: Two decimal places : ${value2}`, () => {
    pm.expect(decimalPlaces2).to.be.lessThan(3);
});

pm.test(`3: Two decimal places : ${value3}`, () => {
    pm.expect(decimalPlaces3).to.be.lessThan(3);
});

pm.test(`4: Two decimal places : ${value4}`, () => {
    pm.expect(decimalPlaces4).to.be.lessThan(3);
});

pm.test(`5: Two decimal places : ${value5}`, () => {
    pm.expect(decimalPlaces5).to.be.lessThan(3);
});

image

1 Like

Hey @mdjones, This is absolutely brilliant.

This work, thank you for the help.