Skip to content

Instantly share code, notes, and snippets.

@KerryJones
Created January 2, 2014 19:49
Show Gist options
  • Select an option

  • Save KerryJones/8225436 to your computer and use it in GitHub Desktop.

Select an option

Save KerryJones/8225436 to your computer and use it in GitHub Desktop.
MySQL function that rounds up to a specific ending, such as "9.99" or "8.88" from any number or any ending.
-- --------------------------------------------------------------------------------
-- Does the CEIL function but goes to a given ending, such as "9.99" or "8.88".
--
-- Example: SELECT ceilEnding( 37.46, 9.99 ) returns 39.99
--
-- @param decimal num
-- @param decimal ending
-- @return decimal
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE FUNCTION `table`.`ceilEnding` ( num DECIMAL(10,2), ending DECIMAL(10,2) )
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
-- Declarations
DECLARE numEnding DECIMAL(10,2);
DECLARE difference DECIMAL(10,2);
DECLARE placeValue INTEGER;
-- Calculations
SET numEnding = SUBSTRING( FORMAT( num, 2 ), -LENGTH( FORMAT( ending, 2 ) ) );
SET difference = numEnding - ending;
SET placeValue = POW( 10, LENGTH( FLOOR( ending ) ) );
-- What to do
IF ( difference > 0 ) THEN
return ROUND( ( num + placeValue - difference ) * 100 ) / 100;
ELSEIF ( difference < 0 ) THEN
return ROUND( ( num - difference ) * 100 ) / 100;
END IF;
-- Nothing to do? Return original number
RETURN num;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment