Need help to build a script to divide two integer fields

giovanni3
Kilo Contributor

How do you divide two integer fields to get a value in a separate field?   For example, field1=10, field2=5.   I want to divide field1 from field2 and have the value in field3.

11 REPLIES 11

geoffcox
Giga Guru

This could be done a couple of ways depending on whether you want to do it client side (on the form you are viewing as fields change) or server side (when storing a record in the database).



On the client script you would have an onLoad client script and two onChange Client scripts. The onLoad script would include the function definition for the math call:



function onLoad() {


  // do nothing, just loading the function below


}



function divide_a_by_b() {


      var a = parseInt(g_form.getValue('field_A'),10);


      var b = parseInt(g_form.getValue('field_B'),10);


      var result = 0; // force to zero if infinite


      if (b != 0) {


              var result = parseInt(a/b,10);


      }


      g_form.setValue('field_C',result);


}



The two onChange scripts would be identical. One of them fires for changes to Field A, and the other for Field B. They both call the function above.



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


  if (isLoading || newValue == '') {


          return;


  }


  divide_a_by_b();


}



A Before Update business rule should also be in place to perform the same math in case the record is changed by some other source than the form (by list editing or by an integration for example):



do_some_math();



function do_some_math() {


      var a = parseInt(current.field_A,10);


      var b = parseInt(current.field_B,10);


      var result = 0;


      if (b != 0) {


              result = parseInt(a/b,10);


      }


      current.field_C = result;


}


Hi Geoff,



Thanks for the quick reply!   It works as expected.   Can we refine it so that it gives the value in C two digits after the decimal (ex. 15,065/3,653=4.12.   With the current script it gives a value of 5.   So, it's rounding up.   Thanks for your help!   This is invaluable for someone like me that cannot program in javascript.


Instead of:




result = parseInt(a/b,10);



Try:



result = (a/b).toFixed(2);



with parseInt you are saying to return an integer, not a decimal.



Some other things to know:



var a = parseInt("15,065",10);     results in a = 15


var b = parseInt("3,653",10);     results in b = 3



The "," in your numbers may throw off your results.


giovanni3
Kilo Contributor

Thanks for the reply!   You are correct!   The comma is throwing-off the result.   Any suggestions on how to correct it?   150,000/300 should show 500 in the C field.   However, it's giving 0.50.