Simple Subtraction

rarootes
Tera Contributor

I have three currency fields, all on the same table. I need to subtract field B from field A and populate field C with the result.

Essentially A - B = C.

I've gone at this from multiple directions, Calculated value, BU, Client script, but none of the Community suggestions have worked for me. What would be the best way to go about this?

1 ACCEPTED SOLUTION

yad_achyut
Giga Guru

Hi ,
If these fields are on a Table there is no need of creating a client script you can simply perform the calculation on the field by using ServiceNow OOB functionality "Calculated Value" under advanced view where you want to get the result of the calculation.

As per your requirement you can write the code on Calculated Value for the Field "C" as :

var firstValue = currrent.A;
var secondValue = current.B;
var result = parseFloat(firstValue) - parseFloat(secondValue);
return result;

This will return the calculated value to the desired variable.


 

View solution in original post

7 REPLIES 7

sachin_namjoshi
Kilo Patron
Kilo Patron

You can configure a client script like below to calculate difference between 2 currency fields.

 

var cur1 = parseInt(g_form.getValue('u_currency_1'));
var cur2 = parseInt(g_form.getValue('u_currency_2'));

var result = cur1 - cur2;

 

Regards,

Sachin

Aman Kumar S
Kilo Patron

Hey,

Use Number() to convert your variables into valid integers and then perform your operation:

Number() converts the type whereas parseInt parses the value of input.

// Parsing
parseInt('32px'); // 32
parseInt('5e1'); // 5

// Convert type
Number('32px'); // NaN
Number('5e1'); // 50

 

Ref link:

https://thisthat.dev/number-constructor-vs-parse-int/

Best Regards
Aman Kumar

SumanthDosapati
Mega Sage
Mega Sage

Hi @rarootes ,

 You need to write two onchange client scripts, one on field A and one on Field B.

Write the client scripts as below.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '') {
      return;
   }

   var A = parseInt(g_form.getValue('field A name here'));
   var B = parseInt(g_form.getValue('field B name here'));

   var output = A - B;
	
   g_form.setValue('field C name here', output);
   
}

 

Mark as correct or helpful if it works.

Regards,

Sumanth

Chetan Mahajan
Kilo Sage
Kilo Sage

Hi Rarootes,

                            As the currency field is Float type you have to use parseFloat, Check below onChange Script on Var B.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var A = g_form.getValue('u_a.display').replace(/,/g, "");
    var B = g_form.getValue('u_b.display').replace(/,/g, "");

    var C = parseFloat(B) - parseFloat(A);
    g_form.setValue('u_c.display', C);
}

Output: 

find_real_file.png

 

Kindly mark correct and helpful if applicable