Truncate (not round) decimal places in SQL Server - sql

I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:
declare #value decimal(18,2)
set #value = 123.456
This will automatically round #value to be 123.46, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the left() function and convert back to a decimal. Are there any other ways?

ROUND ( 123.456 , 2 , 1 )
When the third parameter != 0 it truncates rather than rounds.
Syntax
ROUND ( numeric_expression , length [ ,function ] )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data
type category, except for the bit data type.
length
Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.
function
Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

select round(123.456, 2, 1)

SELECT Cast(Round(123.456,2,1) as decimal(18,2))

Here's the way I was able to truncate and not round:
select 100.0019-(100.0019%.001)
returns 100.0010
And your example:
select 123.456-(123.456%.001)
returns 123.450
Now if you want to get rid of the ending zero, simply cast it:
select cast((123.456-(123.456%.001)) as decimal (18,2))
returns 123.45

Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.
CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))

Do you want the decimal or not?
If not, use
select ceiling(#value),floor(#value)
If you do it with 0 then do a round:
select round(#value,2)

Another truncate with no rounding solution and example.
Convert 71.950005666 to a single decimal place number (71.9)
1) 71.950005666 * 10.0 = 719.50005666
2) Floor(719.50005666) = 719.0
3) 719.0 / 10.0 = 71.9
select Floor(71.950005666 * 10.0) / 10.0

Round has an optional parameter
Select round(123.456, 2, 1) will = 123.45
Select round(123.456, 2, 0) will = 123.46

ROUND(number, decimals, operation)
number => Required. The number to be rounded
decimals => Required. The number of decimal places to round number to
operation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0
SELECT ROUND(235.415, 2, 1)
will give you 235.410
SELECT ROUND(235.415, 0, 1)
will give you 235.000
But now trimming0 you can use cast
SELECT CAST(ROUND(235.415, 0, 1) AS INT)
will give you 235

This will remove the decimal part of any number
SELECT ROUND(#val,0,1)

SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;
Would give you 2 values after the decimal point. (MS SQL SERVER)

Another way is ODBC TRUNCATE function:
DECLARE #value DECIMAL(18,3) =123.456;
SELECT #value AS val, {fn TRUNCATE(#value, 2)} AS result
LiveDemo
Output:
╔═════════╦═════════╗
║ val ║ result ║
╠═════════╬═════════╣
║ 123,456 ║ 123,450 ║
╚═════════╩═════════╝
Remark:
I recommend using built-in ROUND function with 3rd parameter set to 1.

I know this is pretty late but I don't see it as an answer and have been using this trick for years.
Simply subtract .005 from your value and use Round(#num,2).
Your example:
declare #num decimal(9,5) = 123.456
select round(#num-.005,2)
returns 123.45
It will automatically adjust the rounding to the correct value you are looking for.
By the way, are you recreating the program from the movie Office Space?

Try like this:
SELECT cast(round(123.456,2,1) as decimal(18,2))

If you desire to take some number like 89.0904987 and turn it into 89.09 by simply omitting the undesired decimal places, simply use the following:
select cast(yourColumnName as decimal(18,2))
The following screenshot is from W3Schools SQL Data Types section, which describes what decimal(18,2) is doing:
Therefore,
select cast(89.0904987 as decimal(18,2))
gives you: 89.09

Please try to use this code for converting 3 decimal values after a point into 2 decimal places:
declare #val decimal (8, 2)
select #val = 123.456
select #val = #val
select #val
The output is 123.46

I think you want only the decimal value,
in this case you can use the following:
declare #val decimal (8, 3)
SET #val = 123.456
SELECT #val - ROUND(#val,0,1)

I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):
SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)

I think we can go much easier with simpler example solution found in Hackerrank:
Problem statement: Query the greatest value of the Northern Latitudes
(LAT_N) from STATION that is less than 137.2345. Truncate your answer
to 4 decimal places.
SELECT TRUNCATE(MAX(LAT_N),4)
FROM STATION
WHERE LAT_N < 137.23453;
Solution Above gives you idea how to simply make value limited to 4 decimal points. If you want to lower or upper the numbers after decimal, just change 4 to whatever you want.

Mod(x,1) is the easiest way I think.

select convert(int,#value)

Related

Round-up or Round-down the SpecialOfferPrice column in this query?

How can I Round-up or Round-down the SpecialOfferPrice column in this query?
SELECT TB_Product. ProductID,
TB_Product.RetailPrice * 0.95 AS SpecialOfferPrice
Use the below query.
SELECT TB_Product. ProductID,
round(TB_Product.RetailPrice * 0.95) AS SpecialOfferPrice
for more information refer to this [link]https://www.w3schools.com/sql/func_sqlserver_round.asp
Try to use CEILING(numeric) to round up.
According to MSDN:
This function returns the smallest integer greater than, or equal to,
the specified numeric expression.
SELECT
CEILING(TB_Product.RetailPrice * 0.95) AS SpecialOfferPrice
To round down use ROUND.
As MSDN says::
Returns a numeric value, rounded to the specified length or precision.
SELECT ROUND(175.45, 0)
Output is:175.00
UPDATE:
If number is below 200 and you want to round to only one number after the decimal point and if it is above 200, you want to use use CEILING:
DECLARE #delimiter DECIMAL(10,5) = 200
SELECT
CASE
WHEN E.FooNumber < #delimiter THEN ROUND(e.FooNumber, 0)
ELSE CEILING(e.FooNumber)
END AS FooNumbers
FROM (VALUES(100.1),
(180.4),
(250.5),
(350.8)) E(FooNumber)
Try this :
SELECT TB_Product. ProductID,
ROUND(TB_Product.RetailPrice * 0.95, -2) AS SpecialOfferPrice
Use the CEILING(), FLOOR() functions.
This link goes further in explaination (https://www.mssqltips.com/sqlservertip/1589/sql-server-rounding-functions--round-ceiling-and-floor/).
You can use the FLOOR() and CEILING() functions to round up or down respectively.
https://learn.microsoft.com/en-us/sql/t-sql/functions/ceiling-transact-sql?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/t-sql/functions/floor-transact-sql?view=sql-server-ver15

Need help in converting some values in my SQL Table Column to decimal

I have a Varchar column which have data such as 1.025407162E7, 1.268479084E7 basically it contains something called as E7. How can i convert it to decimal ?
I have tried to convert it to decimal, I could have removed the E7 and moved the decimal point 7 steps forward or Add 7 zeros if there are no so many numbers. But I was looking for a right approach to do it.
CONVERT(DECIMAL(27, 7), ETL_AM.BNK_SHR_LGR_BAL_AMT)
So the actual values look different
1.025407162E7 = 10254071.6200000 and 1.268479084E7 = 12684790.8400000
That's a valid float constant for SQL Server. So convert the string to a float, and then to a decimal.
CONVERT(DECIMAL(27, 7), cast(ETL_AM.BNK_SHR_LGR_BAL_AMT as float))
eg
select convert(decimal(27,7), cast( '1.025407162E7' as float) )
returns
10254071.6200000
Okay, So Error_2646 has taken me in right direction. I converted the value to REAL then converted to decimal.
CASE WHEN SF_FAM.FinServ__Balance__c like '%E%' THEN CONVERT(DECIMAL(27, 7), CONVERT(float(27), SF_FAM.FinServ__Balance__c))
ELSE CONVERT(DECIMAL(27, 7), SF_FAM.FinServ__Balance__c) END
If it is an exponential function, a simple select, after converting it to a float can give you the decimal.
SELECT CAST('1.025407162E7' AS FLOAT)
Otherwise, if E is a random character and if you want to do the calculatoin, you can do it using a case statement.
DECLARE #value VARCHAR(100)
SET #value = '1.025407162E7'
SELECT CASE WHEN #value like '%E7%'
THEN (1.025407162 * 10000000)
END

Need to pad zeros left and right for a string value according to decimal format

So if I have a data (varchar) like say 10.1
I need the value as 0000101000000.
means (000010) whole number and (1000000) decimal value.
Its a 13 character string ,numbers coming before decimal point should be in first 6 characters and numbers coming after decimal point should be in last 7 characters
Maybe..?
DECLARE #d decimal(13,7) = 10.1;
SELECT RIGHT('0000000000000' + CONVERT(varchar(13),CONVERT(bigint,(#d * 10000000))),13);
Using my crystal ball here though.
Edit: As, for some reason, the OP is storing a decimal as a varchar (this is a really bad bad idea on it's own), I have added further logic to attempt to convert the value to a decimal first.
As experience has taught many of us, give a user a non-numeric column to store a numeric value in and they're more than happily store a non-numeric value in it, so i have used TRY_CONVERT and assumed you are using SQL Server 2012+:
DECLARE #d varchar(13) = 10.1;
SELECT RIGHT('0000000000000' + CONVERT(varchar(13),CONVERT(bigint,(TRY_CONVERT(decimal(13,7),#d) * 10000000))),13);
SELECT REPLICATE('0',6-LEN(SUBSTRING(CAST([data] AS VARCHAR), 1,
CHARINDEX('.',CAST([data] AS VARCHAR)) -1)))+SUBSTRING(CAST([data] AS VARCHAR), 1,
CHARINDEX('.',CAST([data] AS VARCHAR)) -1)+
SUBSTRING(CAST([data] AS VARCHAR), CHARINDEX('.',CAST([data] AS VARCHAR)) + 1,
LEN(CAST([data] AS VARCHAR)))+REPLICATE('0',7-LEN(SUBSTRING(CAST([data] AS VARCHAR), CHARINDEX('.',CAST([data] AS VARCHAR)) + 1,
LEN(CAST([data] AS VARCHAR))))) AS Whole
FROM Table1
Output
Whole
0000101000000
Demo
http://sqlfiddle.com/#!18/8649d/16
You can use some math and string operations to do it like below
see live demo
declare #var decimal(10,4)
set #var=10.1
select #var,
right(cast(cast(( floor(#var)+ power(10,7)) as int) as varchar(13)),6)
+
cast(cast(((#var- floor(#var)) * power(10,7)) as int) as varchar(13))
There's a fair amount of string manipulation to be done here. I'll step through what I did.
I used a variable for the base number so I could verify different results:
declare #n decimal(9,3) = 10.1
You need 6 spaces left of the decimal and 7 spaces to the right, so I'm doing all the manipulation on a VARCHAR(13). I didn't create a new variable as a VARCHAR because I'm assuming you want to be able to do this conversion in line on the fly, so I'm using that CAST over and over again.
Start by finding the decimal place.
SELECT CHARINDEX('.',CAST(#n as VARCHAR(13)))
In the sample number, that's a 3, but it could obviously change.
Now, get the portion of the number to the left of the decimal place.
SELECT SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1)
Then get the portion to the right of the decimal.
SELECT SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13))))
Pad the leading zeroes. Put 6 on, concatenate, and take a RIGHT 6. Accounts for no digits to the left of the decimal.
SELECT RIGHT(REPLICATE(0,6) + SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1), 6)
Pad the trailing zeroes. Same idea, but in the other direction.
SELECT LEFT(SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13)))) + REPLICATE(0,7),7)
Then put it all together.
SELECT RIGHT(REPLICATE(0,6) + SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1), 6)
+
LEFT(SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13)))) + REPLICATE(0,7),7)
Results.
0000101000000
declare #var varchar(20) = '10000.112'
SELECT FORMAT (FLOOR(#var), '000000') + left((PARSENAME(#var,1)) + replicate('0',7),7)

Sql server rounding issue down to 2 decimal places

I am having a problem getting my "Rounding to 2 decimal places" to behave as I would expect.
Try this trivial example
declare #num numeric (18,2)
declare #vat numeric (18,2)
set #num = 11729.83
set #vat = 1.14
select round(#num/#vat,2)
I am getting an answer of 10289.320000 but I should be getting 10289.33 . The full un rounded number is 10289.324561403508771929824561404 (unless my maths is completely off)
Try this
select cast(round(#num/#vat,3) as decimal(18,2))
Round can either return a value lower than the original, or a value upper than the original. In fact it returns the value closest to the original.
If you want to systematically round a number to its lower or upper value, you could then use FLOOR or CEILING (Thanks #GarethD for refreshing my memory on CEILING...)
select round(floor(100*#num/#vat)/100,2) -> lower value
select round(ceiling(100*#num/#vat)/100,2) -> upper value
Otherwise round will indeed return 10289.32 when the value is strictly lower than 10289.325 (which is the case here)
Try converting to a decimal:
select cast(round(#num / #vat, 2) as numeric(18, 2))
I advocate round() to be explicit about the conversion method.
Try this
declare #num numeric (18,2)
declare #vat numeric (18,2)
set #num = 11729.83
set #vat = 1.14
select round(Convert(Decimal(18,3),(#num/#vat)),2)
I am not sure if I understand correctly. But maybe you've been looking for something like this:
select round(round(round(round(#num / #vat, 5), 4), 3), 2)
You will need to convert it to the appropriate decimal type again:
SELECT CONVERT(DECIMAL(18,2), ROUND(#NUM/#VAT,2))

Splitting decimal in sql

I am getting result as decimal in stored procedure. If I am getting result as 123.45,
I want to split it into 123 and 45. Can anybody help?
use SQL function FLOOR() for getting integer part
and subtract that from the original for the decimal part
You can also make use of ROUND instead of FLOOR.
See section C. Using ROUND to truncate for trucate, and then subtract that from the original.
Be aware that using FLOOR on negative numbers might not give you the required result.
Have a look at this example
DECLARE #Dec DECIMAL(12,8)
SET #Dec = -123.45
SELECT FLOOR(#DEc)
select round(#Dec, 0, 1)
try this;
DECLARE #result DECIMAL(8,2) = 123.45
SELECT CAST(round(#result,0) AS FLOAT)
SELECT REPLACE(#result % 1 ,'0.','')
OR
DECLARE #result decimal(8,2) = 123.45
select PARSENAME(#result, 2) AS LeftSideValue, PARSENAME(#result, 1) AS RightSideValue