Acknowledged

Cannot Calculate Mod (%) with Doubles

I get an error when I try to calculate a mod with two doubles. There is no error when doing the equivalent calculation with a formula.

var a = 5 as Double;  // or 5d
var b = 2 as Double;  // or 2d
var c = a % b;  // ERROR: Cannot perform operation 'mod' on types '$.Toybox.Lang.Double' and '$.Toybox.Lang.Double'.
var d = a - (Math.floor(a/b)) * b;  // No error

Environment:

Mac OS Sequoia 15.1.1 (24B2091)

Connect IQ SDK 7.4.3

Monkey C Extension 1.1.0

VS Code 1.96.4

----------

EDIT: It appears that it's normal for the mod operator to not work with doubles. I would like to recommend mentioning this in the Reference Guide Arithmetic Operators section along with any other exceptions.

  • If you turn off type checking, you get a runtime error which might be a bit clearer

    var a = 5d;
    var b = 2d;
    var c = a % b;

    Error: Unhandled Exception Exception: UnexpectedTypeException: Expected Number/Long, given Double.

    ------

    In other words, you can only do a '%' with a Number or a Long. not on a Float or a Double.  If either a or b is a Float or Double, you get this.

    a and b need to be integers. 32 or 64 bit , so

    var a = 5l;
    var b = 2l;
    var c = a % b;

    or

    var a = 5;
    var b = 2;
    var c = a % b;

    work fine