user2012403
user2012403

Reputation: 205

Bogus math with app scripts

Anyone had an issue with bogus math results when using Google Apps Script? The following is the code, where a/b/c are send from another function. A/b/c are verified with the logger. ? StartPt is fine, but endpt is generating a false value.

function calcTime(a,b,c)  {
  var x;
  var startHr = 8;
  var startMin = 0;
  var startSec=0;
  var startPt;
  var endPt; 
  startPt = (startHr * 60) + startMin + (startSec/60);
  endPt = (a * 60) + b + (c/60);
  Logger.log(endPt);
  x = endPt -startPt;

  return x;
}

flag

I found that the math error is a multiplication factor of 100 (when endPt is calculated, it multiplies the result by 100). What could cause this?

Upvotes: 0

Views: 945

Answers (1)

Mogsdad
Mogsdad

Reputation: 45750

Real number arithmetic is prone to rounding errors in javascript and apps-script. See Is floating point math broken?. If you're watching your function in the debugger, you'll see rounding errors esp. with (c/60). But that's not likely causing a factor-of-100 error.

Most likely, your parameters aren't what you thing they are. If b arrives as a string, for instance, the calculation of (a * 60) + b + (c/60) will effectively ignore b. The other two parameters, however, will get changed to numbers to to complete the multiplication and division operations. (You can avoid that by using b * 1.)

Anyway, to confirm what you're getting as parameters, try replacing the first few lines of your function with this:

function calcTime(a,b,c)  {
  var params = {
    a:{type:typeof a, value:a},
    b:{type:typeof b, value:b},
    c:{type:typeof c, value:c}}
  Logger.log(params);
  var x;
  ...

Verify that you're getting what you need. If any of the parameters are arriving as date objects, for instance, your math will be wildly incorrect. You may just need to enforce types for your data source.

Upvotes: 2

Related Questions