22 In Postgres: SELECT -2 % 24; ?column? ---------- -2 SELECT m...">

Real, mathematical "modular" operation in Postgres?

In Ruby:

-2 % 24
=> 22

In Postgres:

SELECT -2 % 24;
 ?column?
----------
      -2

SELECT mod(-2,24);
 mod
-----
  -2

I can easily write one myself, but I am curious if Postgres has the actual operation of the module, and not the remainder after division.

+4
source share
2 answers
SELECT MOD(24 + MOD(-2, 24), 24);

will return 22 instead of -2

+4
source

It seems that I will not find anything easier than:

CREATE OR REPLACE FUNCTION modulus(dividend numeric, divisor numeric) RETURNS numeric AS $$
DECLARE
  result numeric;
BEGIN
  divisor := ABS(divisor);
  result  := MOD(dividend, divisor);
  IF result < 0 THEN
    result := result + divisor;
  END IF;
  RETURN result;
END;
$$ LANGUAGE plpgsql;
0
source

Source: https://habr.com/ru/post/1533690/


All Articles