diff --git a/doc/site/modules/core/num.markdown b/doc/site/modules/core/num.markdown index 09fb78ae0..e3e978e9a 100644 --- a/doc/site/modules/core/num.markdown +++ b/doc/site/modules/core/num.markdown @@ -164,6 +164,18 @@ itself is returned. Raises this number (the base) to `power`. Returns `nan` if the base is negative. +### **quo**(other) + +Returns the quotient of this number and `other` rounded, if not already an integer, to the nearest integer towards zero. It is equivalent to: `(this/other).truncate`. + +
+System.print(10.quo(4)) //> 2 +System.print(10.quo(-4)) //> -2 +System.print(15.4.quo(3.6)) //> 4 ++ +It is a runtime error if `other` is not a number. + ### **round** Rounds the number to the nearest integer. diff --git a/src/vm/wren_core.c b/src/vm/wren_core.c index d0a121f8c..2bd63f3de 100644 --- a/src/vm/wren_core.c +++ b/src/vm/wren_core.c @@ -791,6 +791,15 @@ DEF_PRIMITIVE(num_pow) RETURN_NUM(pow(AS_NUM(args[0]), AS_NUM(args[1]))); } +DEF_PRIMITIVE(num_quo) +{ + if (!validateNum(vm, args[1], "Other value")) return false; + + double value = AS_NUM(args[0]); + double other = AS_NUM(args[1]); + RETURN_NUM(trunc(value/other)); +} + DEF_PRIMITIVE(num_fraction) { double unused; @@ -1396,6 +1405,7 @@ void wrenInitializeCore(WrenVM* vm) PRIMITIVE(vm->numClass, "...(_)", num_dotDotDot); PRIMITIVE(vm->numClass, "atan(_)", num_atan2); PRIMITIVE(vm->numClass, "pow(_)", num_pow); + PRIMITIVE(vm->numClass, "quo(_)", num_quo); PRIMITIVE(vm->numClass, "fraction", num_fraction); PRIMITIVE(vm->numClass, "isInfinity", num_isInfinity); PRIMITIVE(vm->numClass, "isInteger", num_isInteger); diff --git a/test/core/number/quo.wren b/test/core/number/quo.wren new file mode 100644 index 000000000..2fc057a87 --- /dev/null +++ b/test/core/number/quo.wren @@ -0,0 +1,16 @@ +System.print(10.quo(4)) // expect: 2 +System.print(10.quo(-4)) // expect: -2 +System.print((-10).quo(4)) // expect: -2 +System.print((-10).quo(-4)) // expect: 2 +System.print(15.4.quo(3.6)) // expect: 4 +System.print(15.4.quo(-3.6)) // expect: -4 + +// Divide by zero. +System.print(3.quo(0)) // expect: infinity +System.print((-3).quo(0)) // expect: -infinity +System.print(0.quo(0)) // expect: nan +System.print((-0).quo(0)) // expect: nan +System.print(3.quo(-0)) // expect: -infinity +System.print((-3).quo(-0)) // expect: infinity +System.print(0.quo(-0)) // expect: nan +System.print((-0).quo(-0)) // expect: nan