How to check length of a number or integer within response body

Hi all, I have been searching across many forums how to check in the test the length of a number but couldn’t find right answer.

For instance I got:

pm.environment.set(“IMEI”, _.random(100000000000000,400000000000000));

or auto generated ID within response body e.g. “alternateId”: 963947565902989978,

Now, I need to make sure the number won’t be shorter or longer than 15 digits.
Doing following won’t work a number or integer:
pm.expect(jsonData.IMEI).to.have.lengthOf(15);

Is there any way to check the lenght of a number?

I know I can write following test, but is not what I want.
pm.expect(jsonData.IMEI).to.eql(pm.environment.get(“IMEI”));
pm.expect(jsonData.IMEI).to.be.above(100000000000000);
pm.expect(jsonData.IMEI).to.be.below(400000000000000);

Thank you so much

Hello @Martikwak,

Welcome to the Community :clap:

The easiest way to have the length is to convert the numbers to String and then to toString();

var result = IMEI.toString();

pm.test("Length as expected", () => {
pm.expect(jsonData.result).to.have.lengthOf(15);
});

Else you can use math functions as below:

var length = Math.ceil(Math.log10(IMEI + 1));
console.log(length);
pm.test("Length as expected", () => {
pm.expect(jsonData.length).to.eql(15);
});

I have just worked on roughly based on what you provided. Please let me know if there are any issues and please provide me the full JSON response to work on :wink:

I hope this helps :slight_smile:

1 Like

Thank you so much for prompt reply @bpricilla.
Your solution works like a charm :slight_smile: Very appreciate your help

1 Like

Glad that it worked :blush:

1 Like

Btw, using math functions (second way) the syntax instead of .to.have.lengthOf (15) should be .to.eql (15) otherwise won’t work.
Thanks again, it was a great help and made me to study more about math functions :blush:

1 Like

Yes exactly, that’s because already you are storing the length in the variable. Sorry even I was sharing the rough scripts as I mentioned :slight_smile: Happy learning :trophy: