Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Rounding to nearest 0.05
Message
From
21/05/2018 11:02:45
 
 
To
21/05/2018 10:39:28
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2012
Miscellaneous
Thread ID:
01660219
Message ID:
01660220
Views:
82
This message has been marked as the solution to the initial question of the thread.
>Hi,
>I need to be able to round some totals to the nearest 0.05.
>
>I have done this in C# using this code:
>
>
        public static decimal RoundToNearest(decimal value, decimal nearest)
>        {
>            decimal remainder;
>            decimal returnValue;
>
>            remainder = value % nearest;
>            if (remainder >= (nearest/2))
>        	{
>                returnValue = value + (nearest - remainder);
>        	}
>            else
>            {
>                returnValue = value - remainder;
>            }
>            return returnValue;
>        }
>
>Is there a way to do this in SQL Server? Shall I just try to use the same logic in a UDF?
>
>I will need to use it in queries like:
>
>SELECT RoundToNearest(SUM(SomeAmount), 0.05) AS RoundedTotal

As a function:
create function dbo.RoundToNearest (@value float, @nearest float)
returns float
as
	begin
		return round(@value / @nearest, 0) * @nearest;
	end;
go

select dbo.RoundToNearest(17.08, 0.05)
go
Inline in a Select statement:
SELECT ROUND(17.08 / 0.05) * 0.05
----------------------------------
António Tavares Lopes
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform