Modulo Operation on Floating Point Numbers on Postgresql

Modulo Operation on Floating Point Numbers on Postgresql

I wish to perform a modulo operation between two floating point integers in PostgreSQL. Specifically, I wish to enforce angle-arithmetic, e.g. forcing angles to lie in the interval [0,2*pi] after some mathematical operations.

I can see fmod or such is not officially supported in SQL. Is there any reasonable workaround?

5

1 Answer

It is trivial to create such a function yourself:

CREATE FUNCTION fmod (
   dividend double precision,
   divisor double precision
) RETURNS double precision
    LANGUAGE sql IMMUTABLE AS
'SELECT dividend - floor(dividend / divisor) * divisor';

You can use that to solve your problem:

SELECT fmod(1000, 2.0 * pi());

       fmod        
-------------------
 0.973536158445768
(1 row)

This function can be inlined, so it should be pretty efficient.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.