Variable precision in a column in SQL - sql

I have a column which consists of three different types of numbers:
Type 1 has no digits after decimal point like 5, 17, etc.
Type 2 has one digit after decimal point like 27.5, 11.8, etc.
Type 3 has 2 digits after decimal points like 227.64, 35.77, etc.
I want the Type 1 numbers to have a 0 after decimal point so that they become 22.0, 11.0 and so on while the Type 2 and Type 3 numbers remain unaffected.

Can be done by pushing value into a string.
DECLARE #table AS TABLE (myValue FLOAT)
INSERT INTO #table
(myValue)
VALUES (5),
(17),
(27.5),
(11.8),
(227.64),
(35.77)
SELECT CASE WHEN CAST(myValue AS VARCHAR(20)) LIKE '%.%' THEN CAST(myValue AS VARCHAR(20))
ELSE CAST(myValue AS VARCHAR(20)) + '.0'
END
FROM #table
This is a poor solution at best. Your better maintaining your data in its original format and then handling your formatting in the presentation layer as already stated by Ankit. I know its not always possible, but the data place is not really the place to do this.

What is the data type of the column?
Try:
SELECT
CASE
WHEN LEN(RIGHT([MyColumn], CHARINDEX('.', REVERSE([MyColumn])))) >= 3
THEN [MyColumn]
ELSE CAST(CAST([MyColumn] AS NUMERIC(8,1)) AS NVARCHAR(10))
END AS [MyColumn]
FROM [MyTable]

Related

Removing trailing zeros in case statement

I've been trying to remove the trailing zeros from a column of a table. It works well when I try to remove the zeros from the column. However, when I use it with a case statement (to remove the zeros when a flag is turned on, and to keep them when a flag is turned off) it doesn't work properly. It doesn't recognize the flag. For example, I've hard coded the column as a constant value; while 1=0 (false), it is retrieving the value removing the zeros. It should be true in the else statement.
SELECT CASE WHEN 1=0 THEN cast(CAST(123.45000 AS decimal(6,2)) as float)
ELSE
'123.456700'
END
SELECT CASE WHEN 1=0 THEN CONVERT(DOUBLE PRECISION, 123.456700)
ELSE
'123.456700'
END
Why is this happening? Can anyone help me with this?
The above is well explained by #Tim below.
However, it doesn't remove the zeros at all in a table. It doesn't recognize the flag at all. Here is an example:
CREATE TABLE #tablea
(item CHAR(2), name VARCHAR(10), amount DECIMAL(9,2))
INSERT INTO #tablea
VALUES ('AB', 'D1', 1.10),
('AB', 'D2', 1.00),
('AB', 'D3', 0.90),
('AB', 'D4', 0.09)
DECLARE #flag INT = 1
SELECT CASE WHEN #flag = 1
THEN CAST(CAST(amount AS DECIMAL(6,2)) AS VARCHAR(max))
ELSE amount END
FROM #tablea
As #JNevill commented, what is happening here is that an implicit conversion is happening in the ELSE branch of your CASE expression, converting the string literal into a float, thereby removing the trailing zeroes when it gets printed. One option would be to cast the IF portion to VARCHAR:
SELECT
CASE WHEN 1=0
THEN CAST(CAST(123.45000 AS decimal(6,2)) AS varchar(max)) -- a string
ELSE '123.456700' END -- also a string
Demo
Note that in certain versions of SQL (other than yours) your CASE expression would not even run without error. It just so happens that a silent conversion is taking place here.
You can't remove trailing zeroes from a decimal data type. The decimal/numeric data types are fixed point data type:
Numeric data types that have fixed precision and scale. Decimal and numeric are synonyms and can be used interchangeably.
This means that the decimal point is in a fixed position within the stored number, unlike float and read which are floating point data types - so for a decimal(9,2) there will always be two digits to the right of the decimal point - and for numeric(5,3) where will always be three digits to the left of the decimal point.
If precision is not very important, you can convert to float - but you should be aware that unlike decimal, float is an approximate data type.
Please note that you would still have to convert both branches of the case statement to a varhcar otherwise SQL Server will implicitly convert both branches to float and it will look like the flag is being ignored.
DECLARE #flag INT = 1
SELECT
CASE WHEN #flag = 1
THEN CAST(CAST(amount AS float) as varchar(30))
ELSE CAST(amount as varchar(30))
END As [Remove trailing zeros],
-- This is to show the opposite branch
CASE WHEN #flag = 0
THEN CAST(CAST(amount AS float) as varchar(30))
ELSE CAST(amount as varchar(30))
END As [Include trailing zeros]
FROM #tablea
Results:
Remove trailing zeros Include trailing zeros
1.1 1.10
1 1.00
0.9 0.90
0.09 0.09
#Tim, thanks. It works in the demo you showed. But it doesn't remove the zeros at all in a table. It doesn't recognize the flag at all. Here is an example:
CREATE TABLE #tablea
(item CHAR(2), name VARCHAR(10), amount DECIMAL(9,2))
INSERT INTO #tablea
VALUES ('AB', 'D1', 1.10),
('AB', 'D2', 1.00),
('AB', 'D3', 0.90),
('AB', 'D4', 0.09)
DECLARE #flag INT = 1
SELECT CASE WHEN #flag = 1
THEN CAST(CAST(amount AS DECIMAL(6,2)) AS VARCHAR(max))
ELSE amount END
FROM #tablea

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 How to convert number to text with minimum decimal places (dynamic number of decimal places) in SQL

In an SQL query, I want to convert numeric value to text with minimum no. of decimal places, example if the number is 2.50, then I want output as 2.5; if number is 3, then I want output as 3; if number is 18.75, I want output as 18.75, etc.
How can I achieve this?
EDIT 1:
To give more background, I am dividing 2 numeric values, and want the result in text with minimum required decimal places.
Thanks.
In SQL 2012 and above you can write
SELECT FORMAT(15.0/4.0 , '#.########' )
It uses FORMAT function which uses .NET String.Format functionality.
If want to get 2 decimals for division values, use this
Select case when right(cast ( x/y as decimal(18,2)),1) = 0
then left (cast ( x/y as decimal(18,2)),3)
else cast ( x/y as decimal(18,2)) end ReqOutput
This should do the trick...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
SomeNumber DECIMAL(9,7) NOT NULL
);
INSERT #TestData (SomeNumber) VALUES
(1.2345670), (1), (99.00100), (5.55);
SELECT
td.SomeNumber,
REVERSE(STUFF(rcv.RevCastVarchar, 1, PATINDEX('%[^0.]%', rcv.RevCastVarchar) - 1, ''))
FROM
#TestData td
CROSS APPLY ( VALUES (REVERSE(CAST(td.SomeNumber AS VARCHAR(10)))) ) rcv (RevCastVarchar);
HTH,
Jason

Converting a mixed fraction to a float number in Netezza

I have a field with numbers stored as text in 3 formats:
xx. (example: 31.)
xx.x (example: 31.2)
xx x/x (example: 31 2/7)
For the final result, I need all numbers to be in decimal format (that is, xx.x).
Converting the first two formats into decimals is fairly simple, but I haven't quite figured out how to convert the last case, as a simple CAST function doesn't work. I've used the INSTR function to isolate all the fractional cases of these numbers, but I don't know where to go from there. I've looked at other examples but some of the functions referenced (like SUBSTRING_INDEX) don't exist in Netezza.
I think #Niederee has the solution from brute force, but I'd use the sql extensions toolkit.
create temporary table fractions (
val nvarchar(64)
) distribute on random;
insert into fractions values ('2.');
insert into fractions values ('2.3');
insert into fractions values ('31 2/7');
insert into fractions values('2 0/8');
insert into fractions values('516 56/537');
select
val
,case
when regexp_like(val,'^[\d\.]+$') then val::numeric(20,10) --Cast it if we can.
when regexp_like(val,'^[\d\.\s\/]+$')
then regexp_extract(val,'\d+',1,1)::numeric(20,10) --Whole.
+ (
regexp_extract(val,'\d+',1,2)::numeric(20,10) --Numerator.
/ regexp_extract(val,'\d+',1,3)::numeric(20,10) --Denominator.
)
else null
end
from
fractions;
Try the following:
create temp table so_test (
txt_val varchar(100)
);
insert into so_test values ('31.');
insert into so_test values ('31.2');
insert into so_test values ('31 2/7');
select txt_val
, cast(decode(substr(txt_val,1,instr(txt_val,' ')),'',txt_val,substr(txt_val,1,instr(txt_val,' '))) as numeric(18,2)) as root
,cast(substr(txt_val,instr(txt_val,' ')+1,length(txt_val)-instr(txt_val,'/')) as numeric(18,2))
/cast(substr(txt_val,instr(txt_val,'/')+1,length(txt_val)) as numeric(18,2)) as fraction
,cast(root + case when fraction = 1 then 0 else fraction end as numeric(3,1)) as num_val
from so_test
Thanks for the help everyone. I forgot to close this out, I actually figured out a way to do it:
select
case when instr(num,'/') > 0 then
cast(substr(num,1,2) as float)
+ (cast(substr(num,4,1) as float)/cast(substr(num,6,1) as float))
when instr(num,'.') > 0 then cast(substr(num,1,4) as float)
else cast(num as float)
end as float_num

Truncate (not round) decimal places in SQL Server

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)