I am trying to write a script that will add 5% to a subtotal and no matter what I try it won’t work. Here is an example. I know Excel formulas, but don’t write Javascript, please help.
// (Function added as source of dummy data)
function getField(key) {
return ({
EXTENSION1: {value:'110.0'},
EXTENSION2: {value:'95.0'},
EXTENSION3: {value:'85.0'},
EXTENSION4: {value:'65.0'},
EXTENSION5: {},
'GE%': {value: '5'},
})[key]
}
var extension1 = this.getField("EXTENSION1").value;
var extension2 = this.getField("EXTENSION2").value;
var extension3 = this.getField("EXTENSION3").value;
var extension4 = this.getField("EXTENSION4").value;
var extension5 = this.getField("EXTENSION5").value;
var sum = parseFloat(extension1) + parseFloat(extension2) + parseFloat(extension3) + parseFloat(extension4) + parseFloat(extension5);
var percentage = parseFloat(this.getField("GE%").value);
var result = sum * (percentage / 100);
console.log(result);
I’ve entered this code and it’s not producing a value
2
Answers
I have created this snippet to implement your solution and it works for me:
Key ideas:
NaN
sum
withpercentage / 100
, but you want to add that tosum
, which means that you need100 + percentage
instead of just `percentageresult
Your code doesn’t properly account for when a field hasn’t been filled out.
A better solution
You can use detect if a value is
NaN
and instead set it to 0. The parts I edited are between the markers.An okay solution
Your updated summation code could simply fail-over to
0
if the string is empty.Why?
Passing an empty string to
parseInt
results inNaN
: