ERPNext Conference 2019* ERPNext.com Blog

Set value of a field to be always positive and a case of division by zero

timesheets
script
custom_script
erpnext

#1

I have 3 fields as below;

  1. overtime_total (field type: float)
  2. gross_total (field type: float) 0/-
  3. overtime_percent (field type: float)

The value of “overtime_percent” field is calculated as (overtime_total / gross_total * 100)

I have written the following custom script to achieve this:

frappe.ui.form.on("Charges", "overtime_total", function(frm) {
frm.set_value("overtime_percent", flt(frm.doc.overtime_total) / flt(frm.doc.gross_total) * 100);
});

frappe.ui.form.on("Charges", "gross_total", function(frm) {
frm.set_value("overtime_percent", flt(frm.doc.overtime_total) / flt(frm.doc.gross_total) * 100);
});

Now the problem arises for 2 cases as below:

Case 1: When value of “gross_total” field is 0, then the value of “overtime_percent” is shown as INFINITY (obviously since its a divide by 0), but for this case I want to set the value of “overtime_percent” as simply 0 instead of INFINITY

Case 2: When value of “gross_total” field is negative (-10, -25, etc.) then the value of “overtime_percent” is shown as a negative value, but I want to show the value of “overtime_percent” to always show as a positive number.
For eg.:
overtime_total: 50
gross_total: -200
overtime_percent: -25 (this should be shown as 25 instead of -25)

Any help is appreciated. Thanks :slightly_smiling_face:


#2

frm.set_value(“overtime_percent”, Math.abs (flt(frm.doc.overtime_total) / flt(frm.doc.gross_total) * 100));
You can use abs method to show positive number.


#3

Tried this already but not working.
Also tried fabs() and fabsf() arguments but not working.


#4

so before setting value convert gross_total into positive number then set the value for overtime_percent.
Math.abs() should have worked, what error did you get?


#5

The field “gross_total” is shown on the form so it should be correctly shown as a negative figure. Only the “overtime_percent” field should be calculated and shown as positive.

If I convert the “gross_total” to positive before setting value of “overtime_percent” then it wrongly shows gross total field as a positive even if the user has put in a negative value there.

Tired using abs, fabs, fabsf, math.abs but the “overtime_percent” field does not calculate at all if any of these is used.


#6

@ROHAN_JAIN1

Any further possible help on this?

  1. Set the value as positive only
  2. Division by 0 case

Thanks for your help till now. Really appreciate it :+1:


#7
cur_frm.set_value("overtime_precentage",(flt(cur_frm.doc.gross_total) == 0) ? 0 :Math.abs( flt(cur_frm.doc.over_time) / flt(cur_frm.doc.gross_total) * 100));  

I hope now it will work according to your need.


#8

Hi @ROHAN_JAIN1

This code works wonderfully! Fulfills both the cases.

Thanks a lot for your help :grin: :pray: