Remove decimal places without rounding

,

There was a script here not too long ago which showed how to 'truncate' a number to two decimal places without rounding. This used a lot of casts to varchars and back.
The solution worked, but I knew there had to be a way of doing exactly this without having to go back and forth between numeric and character data. The result is the UDF below.

In words, here is what the script does:
- Round the number to the specified number of decimal places. This can go either up or down.
- If the result is bigger than the input value, calculate and substract the minimum value allowed by the number of decimal places specified.

The only 'tough' bit in the UDF is the last bit, calculating the minimum value allowed by the number of decimal places. To do this we use the following formula:

1 / 10 ^ Decimals
(^ taken as the power operator, T-SQL uses the Power() function for this instead)

Example: 1 / 10 ^ 2 = 1 / 100 = .01

Because SQL Server likes to see whole numbers as integers, we need to explicitly convert both arguments for the Power() function to floats in order to get a float result. If we don't do that .01 is cast to an integer resulting in 0.

CREATE FUNCTION RemoveDecimalsWithoutRounding
(	@InputValue Float
,	@Decimals Int
)

-- Get the rounded value
DECLARE @ReturnValue Float;
SET @ReturnValue = Round(@InputValue, @Decimals);

-- If the value is too high remove the smalles value allowed by the specified number of decimal places
IF @ReturnValue > @InputValue
	SET @ReturnValue = @ReturnValue - (1 /  Power(Convert(Float, 10), Convert(Float, @Decimals)));

PRINT @ReturnValue;

Rate

Share

Share

Rate