Reputation: 13491
A consultant has described a type of rounding I need to use in a financial application.
The following value: 0.01488
needs to be rounded in steps like this. We round each digit at a time,
0.0148 -> 0.015
0.015 -> 0.02
Thus the result is 0.02 (2 cents).
But if we did normal rounding to 2 dp the value 0.0148 would round to 0.01.
What is the name of this rounding? And how can I do it with SQL Server?
Update:
My example above is an arbitrary example. The starting value might be 0.15436798, i.e. any number of decimal places. It is related to the result of a previous multiplication. In that case I would need to round more times.
Upvotes: 1
Views: 607
Reputation: 1334
You can create a scalar function to do this job. like:
CREATE function [dbo].[fn_roundx]( @num FLOAT,@round INT)
RETURNS FLOAT
AS
BEGIN
DECLARE @count INT=10;
WHILE @count > = @round
BEGIN
SET @num = ROUND(@num,@count);
SET @count=@count-1;
END;
RETURN @num
END
And then use it as per your conveneince for any depth of rounding you want? For example
DECLARE @num FLOAT=0.014887;
SELECT @num AS ActualNumber,dbo.fn_roundx(@num,2) AS RoundedNumber
or
DECLARE @num FLOAT=0.014887;
SELECT @num AS ActualNumber,dbo.fn_roundx(@num,3) AS RoundedNumber
Sounds good?
Upvotes: 1
Reputation: 1334
How about something like following?
DECLARE @num decimal(20,5)=0.014880;
DECLARE @count INT=5;
DECLARE @round INT=2;
SELECT @num value;
WHILE @count > = @round
BEGIN
SET @num = ROUND(@num,@count);
SET @count=@count-1;
END;
SELECT @num value;
with following output..
for any number up to any number of round
you want?
Upvotes: 1
Reputation: 404
Try this,
select round(round(0.01500,3),2)
select round(round(0.01488,3),2)
Upvotes: 0
Reputation: 93694
Use ROUND
function twice
First time pass length as 3
to round 0.01488
to 0.01500
SELECT Round(0.01488, 3) -- 0.01500
On top of it pass length as 2
to round 0.01500
to 0.02000
SELECT Round(0.01500, 2) -- 0.02000
finally it should be something like this
DECLARE @num NUMERIC(16, 5) = 0.01488
SELECT Round(Round(@num, 3), 2)
Upvotes: 0