Copy link to clipboard
Copied
Hi there, I have this problem when a cell has value of zero, then the answer returned is blank.
I am not sure how to resolve this problem.
For example:
In the above image, I have applied the code below but it returns the answer as blank.
I expected the answer to be 1.1
which can be calculated by:
(top - bkg) / ((top-bkg)+(bottom-bkg)) *100
(0.1-0)/((0.1-0)+(9-0))*100
= 1.1
var v1 = Number(this.getField("Top").valueAsString);
var v2 = Number(this.getField("Bottom").valueAsString);
var v3 =
Number(this.getField("Bkg").valueAsString);
if(v3){
if(v1=="" || v2=="") event.value = "";else
event.value = (v1-v3)/((v2-v3)+(v1-v3))*100;}
else
event.value = "";
Any idea what's wrong with my code? Thanks
Copy link to clipboard
Copied
You can replace your code with the following code, which should work correctly:
var topValue = Number(this.getField("Top").value);
var bottomValue = Number(this.getField("Bottom").value);
var bkgValue = Number(this.getField("Bkg").value);
if (isNaN(topValue) || isNaN(bottomValue) || isNaN(bkgValue)) {
event.value = "";
} else if (topValue === 0 && bkgValue === 0) {
event.value = "";
} else {
var numerator = topValue - bkgValue;
var denominator = (topValue - bkgValue) + (bottomValue - bkgValue);
if (denominator === 0) {
event.value = "";
} else {
event.value = (numerator / denominator) * 100;
}
}
Copy link to clipboard
Copied
I think you mixed fields and variables, you sure v3 should be Bkg field?
Because v3 is 0 (Bkg) so it sets the field empty.
Copy link to clipboard
Copied
You can replace your code with the following code, which should work correctly:
var topValue = Number(this.getField("Top").value);
var bottomValue = Number(this.getField("Bottom").value);
var bkgValue = Number(this.getField("Bkg").value);
if (isNaN(topValue) || isNaN(bottomValue) || isNaN(bkgValue)) {
event.value = "";
} else if (topValue === 0 && bkgValue === 0) {
event.value = "";
} else {
var numerator = topValue - bkgValue;
var denominator = (topValue - bkgValue) + (bottomValue - bkgValue);
if (denominator === 0) {
event.value = "";
} else {
event.value = (numerator / denominator) * 100;
}
}
Copy link to clipboard
Copied
Thanks heaps for this. It works like a champ.
Can you briefly explain what's wrong with my code?
Copy link to clipboard
Copied
As Nesa already point out, in your script:
if(v3){
...your script}
else
event.value = "";
Well, v3 is 0 (Bkg) in your example, so it triggers 'else' part and set value to "".
Copy link to clipboard
Copied
@kenneth kam chuh21426993the script posted by @Saher Naji will not work correctly.
If you input (Top) 0.1 and (Bottom) 9 it will calculate 1.1 even if (Bkg) is blank, shouldn't (Bkg) be 0?
If you first input (Top) 0.1 while other fields are blank, it will calculate 100.
It may give you unwanted behavior.
Copy link to clipboard
Copied