Skip to main content
kenneth kam chuh21426993
Known Participant
September 21, 2023
Answered

Answer return as blank when input values are zero?

  • September 21, 2023
  • 2 replies
  • 1238 views

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

 

This topic has been closed for replies.
Correct answer Saher Naji

Hi @kenneth kam chuh21426993 

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;
  }
}

 

2 replies

Saher Naji
Saher NajiCorrect answer
Inspiring
September 21, 2023

Hi @kenneth kam chuh21426993 

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;
  }
}

 

kenneth kam chuh21426993
Known Participant
September 22, 2023

Thanks heaps for this. It works like a champ. 

Can you briefly explain what's wrong with my code? 

Inspiring
September 22, 2023

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 "".

Nesa Nurani
Community Expert
Community Expert
September 21, 2023

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.