Trying to return an integer, but keep getting a float.

Kristoffer Mon1
Giga Expert

I am getting some strange behavior when trying to return an integer in a Scripted Rest API response. So given the sample the below, the field u_birth_month is set to an integer in the table sys_user.

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

	var user_list = [];
	
	var gr = new GlideRecord("sys_user");
	gr.orderBy('employee_number');
	gr.addNotNullQuery('u_birth_month');
	gr.query();
	
	while (gr.next()) {
		
		//var int_value = Number(gr.getValue('u_birth_month'));
		//var int_value = Math.floor(parseFloat(gr.getValue('u_birth_month')));
		//var int_value = parseInt(gr.getValue('u_birth_month'));
		//var int_value = parseInt("6");
		//var int_value = 6;
		var int_value = parseInt(gr.getValue('u_birth_month'));
		
		var user_obj = {
			employee_number: gr.getValue("employee_number"),
			u_birth_month: int_value

		};

		user_list.push(user_obj);

	}

	return user_list;

})(request, response);

When testing the call in PostMan, u_birth_month is always returning a decimal. Nothing that i've tried (see the commented lines within the while loop) seems to work in removing the decimal.

find_real_file.png

I initially though that perhaps Postman was rendering all integers as decimals, but that is not the case as I can simply hardcode an integer and it renders correctly in Postman.

 

1 ACCEPTED SOLUTION

The idea is that both JavaScript and Rhino/Java represent numbers as floats. Perhaps that is why when Java represents the integer 6 it adds one decimal. Also I doubt you can do something about it.

I suppose if the receiving end can't handle integers expressed with decimals, you can do it hard core: generate the JSON yourself, and use response.getStreamWriter() to obtain a pointer to the output stream and write your JSON string to it. For inspiration, you could have a look at Scripted REST Resource named GetCITypes.

View solution in original post

14 REPLIES 14

Harsh Vardhan
Giga Patron

Can you try with getDisplayValue() instead getValue()?

Hi there. I have tried getDisplayValue() with the same results.

Have you tested in rest API explorer , is it giving the same result. 

Actually rest api explorer provides the expected results:
find_real_file.png

 

But calling the endpoint via the browser always renders the birth month as a decimal:

find_real_file.png