T-SQL - CAST char with leading zeros to int - sql

I'd like to convert char with leading zeros to int, ex '00010' to 00010. I've tried to use CAST or CONVERT :
select CONVERT(int, '00010')
but the function removes zeros at the beginning and return 10 instead of 00010.
Do you know any easy solution to this? The length of input will be allways 5.

Mathematically, leading zeros are meaningless, so an Int can't have leading zeros.
If you need to display leading zeroes, you can always convert to varchar and use concatenation with right, like this:
DECLARE #MyVal int = 10;
SELECT RIGHT('00000' + CAST(#MyVal as varchar(5)), 5)

You must read about data types. An INT is noting more than a bit pattern. Whenever you see the number in a human readable format, the actual value is translated to a string consisting of digits. But this digit format is not the actual INT.
Leading Zeros are never part of the INT itself, but may be added to the string representation. So your question (taken literally) does not make any sense actually.
If there is a string like 00012 and you want to use it like a number, you should just cast it:
SELECT CAST('00012' AS INT) + 2; --14
Other answers show you some approaches to get a padded string representation out of an INT, but this is the opposite direction:
SELECT REPLACE((STR(12,5),' ','0'); --00012
You can combine these approaches:
DECLARE #PaddedNumber CHAR(5)='00012'
SELECT REPLACE(STR(CAST(#PaddedNumber AS INT) + 2,5),' ','0'); --00014
The padded number (which is - by type! - a string) is casted to an INT, then used in computation. The result is an INT, which can be converted to a padded string. But the final result's type is string...

SELECT FORMAT(CONVERT(INT,'00010'), 'd5')
should solve the problem :)

Related

Remove all trailing decimal points from a number stored as a string

I have a couple of strings (nvarchar data type), one is a whole number and one has decimal points trailing. My goal is to remove decimals and have all values as a whole number.
I tried the code below but it gives me an error for the value with no decimals. Is there a way to accomplish this without a case expression. I'll be using this new column in a join.
SELECT [SOW]
--,LEFT([SOW], CHARINDEX('.', [SOW])-1) as 'TestColumn'
FROM [dbo].[t_Schedule_kdm]
WHERE sow in ('15229.11','11092')
Output:
11092
15229.11
My desired Output:
11092
15229
Just append a dot character so that you'll always find an index:
LEFT(SOW, CHARINDEX('.', SOW + '.') - 1)
It's not clear whether you need to cast the result of that expression to an integer value.
Convert first to the most precision number you could ever have e.g. decimal(9,2) then convert to an int. You can't convert directly from a decimal string to an int.
SELECT [Value]
, CONVERT(int,CONVERT(decimal(9,2),[Value]))
FROM (
VALUES ('15229.11'),('11092')
) x ([Value]);

Why does SQL float casting to string not work with LIKE but SQL float casting to decimal to string does work?

I have an object with an number of type float, and I was curious why the following SQL statement does not work, but the one below it does.
SELECT TOP (1000) [number]
FROM [object]
WHERE CONVERT(varchar(255), number) LIKE '%201608147%'
Results in "0 rows found".
SELECT TOP (1000) [number]
FROM [object]
WHERE CONVERT(varchar(255), CONVERT(decimal(20, 2), number)) LIKE '%201608147%'
Results in 1 row found
Edit: I was asked to execute the following:
SELECT
number,
CONVERT(varchar(255), number),
CONVERT(varchar(255), CONVERT(decimal(20, 2), number))
FROM [object]
This yielded the following result:
number : 201608147
number cast to string: 201608147
number cast to decimal: 201608147.00
To show it is really a float:
After simulation I found the following:
select nbr, Convert(varchar(255), nbr), Convert(varchar(255), Convert(decimal(20,2), nbr)) from tbl_XYZ
201608147 2.01608e+008 201608147.00
The Convert(varchar(255), nbr) returns the scientific notation of the number at hand as a string value; consequently the value does not match your pattern :
LIKE '%201608147%'
The reason behind this behavior is that the Float DataType is used to hold the binary (base-2) approximation of a number and not a precise decimal value.
Floating point numbers are often shown in scientific notation. These types are used when range is more important than absolute precision.
The numbers quickly become unwieldy in other formats. Scientific notation also helps to emphasise the limited precision.
You can see the different ways that different functions can be used to format floating-point numbers in this example.
DECLARE #float float = 201608147;
SELECT TheNumber = #float;
SELECT ConvertWithoutStyle = CONVERT(varchar(255),#float),
ConvertWithStyle0 = CONVERT(varchar(255),#float,0),
ConvertWithStyle1 = CONVERT(varchar(255),#float,1),
ConvertWithStyle2 = CONVERT(varchar(255),#float,2),
ConvertWithStyle3 = CONVERT(varchar(255),#float,3);
For a float, style can have one of the values shown below. Other values are processed as 0.
Value Output
0 (default) A maximum of 6 digits. Use in scientific notation, when appropriate.
1 Always 8 digits. Always use in scientific notation.
2 Always 16 digits. Always use in scientific notation.
3 Always 17 digits. Use for lossless conversion. With this style, every distinct float or real value is guaranteed to convert to a distinct character string.
You are using an implicit conversion from float to varchar(255), which implicitly uses style 0. Your float has more than six digits, so it is represented in scientific notation.
You might like to use STR or FORMAT instead.

Conversion fails when trying to Convert string to int

I have some sales numbers in a string column that I need to convert to some format so that i can calculate them with each other but I get this error while trying to convert them.
Conversion failed when converting the varchar value '-6.353,35' to data type int.
I'm not allowed to lose any money by rounding it up. It doesnt mather but in what type i convert as long as im not rounding them up. What's your thoughts?
For example i have -6.353,35 and 300,30 and i want to sum them too -6.053,05
try this...
select convert(int,convert(float,replace('-6.353,35',',','')))
as there are (,) Commas it cannot be converted to float,so remove the (,)commas after converting to float we can convert to int
If you want decimal values, then you should use float
select convert(float,replace('-6.353,35',',',''))
Edit
Like #marc_s suggested, it is preferred to use decimal rather than float
select convert(decimal,replace('-6.353,35',',',''))
Firstly, you want to convert this to a decimal value, not an int, as you will lose anything after decimal point otherwise.
The problem here is the separators that are being used when storing your values.
With your numbers, you have points . to represent thousand separators and commas , to represent decimal points.
To enable you to convert the value to a valid decimal you need to have it in a format that SQL Server can process.
A simple way to do this would be to remove/replace the problem characters before trying to convert the value:
DECLARE #val AS VARCHAR(10) = '-6.353,35'
-- step 1: remove thousand separator
SET #val = REPLACE(#val, '.', '')
SELECT #val AS RemoveThousandSeparator
-- step 2: replace decimal separator with decimal point
SET #val = REPLACE(#val, ',', '.')
SELECT CONVERT(DECIMAL(18,2), #val) AS DecimalPointAdded
-- to do it in one statement:
SET #val = '-6.353,35'
SELECT CONVERT(DECIMAL(18,2),
REPLACE(REPLACE(#val, '.', ''), ',', '.')) AS NumericeRepresentation
Aside from this, you would be much better off storing numeric values in the correct format in the first place to avoid this kind of workaround.

SQL server 'like' against a float field produces inconsistent results

I am using LIKE to return matching numeric results against a float field. It seems that once there are more than 4 digits to the left of the decimal, values that match my search item on the right side of the decimal are not returned. Here's an example illustrating the situation:
CREATE TABLE number_like_test (
num [FLOAT] NULL
)
INSERT INTO number_like_test (num) VALUES (1234.56)
INSERT INTO number_like_test (num) VALUES (3457.68)
INSERT INTO number_like_test (num) VALUES (13457.68)
INSERT INTO number_like_test (num) VALUES (1234.76)
INSERT INTO number_like_test (num) VALUES (23456.78)
SELECT num FROM number_like_test
WHERE num LIKE '%68%'
That query does not return the record with the value of 12357.68, but it does return the record with the value of 3457.68. Also running the query with 78 instead of 68 does not return the 23456.78 record, but using 76 returns the 1234.76 record.
So to get to the question: why having a larger number causes these results to change? How can I change my query to get the expected results?
The like operator requires a string as a left-hand value. According to the documentation, a conversion from float to varchar can use several styles:
Value Output
0 (default) A maximum of 6 digits. Use in scientific notation, when appropriate.
1 Always 8 digits. Always use in scientific notation.
2 Always 16 digits. Always use in scientific notation.
The default style will work fine for the six digits in 3457.68, but not for the seven digits in 13457.68. To use 16 digits instead of 6, you could use convert and specify style 2. Style 2 represents a number like 3.457680000000000e+003. But that wouldn't work for the first two digits, and you get an unexpected +003 exponent for free.
The best approach is probably a conversion from float to decimal. That conversion allows you to specify the scale and precision. Using scale 20 and precision 10, the float is represented as 3457.6800000000:
where convert(decimal(20,10), num) like '%68%'
When you are comparing number with LIKE it is implicitly converted to string and then matched
The problem here is that float number is not precise and when it is converted you can get
13457.679999999999999 instead of 13457.68
So to avid this explicitly format number in appropriate format(not sure how to do this in sql server, but it will be something like)
SELECT num FROM number_like_test
WHERE Format("0.##",num) LIKE '%68%'
The conversion to string is rounding your values. Both CONVERT and CAST have the same behavior.
SELECT cast(num as nvarchar(50)) as s
FROM number_like_test
Or
SELECT convert(nvarchar(50), num) as s
FROM number_like_test
provide the results:
1234.56
3457.68
13457.7
1234.76
23456.8
You'll have to use the STR function and correct format parameters to try to get your results. For example,
SELECT STR(num, 10, 2) as s
FROM number_like_test
gives:
1234.56
3457.68
13457.68
1234.76
23456.78
Pretty well solved already, but you only need to CAST once, not twice like the other answer suggests, LIKE takes care of the string conversion:
SELECT *
FROM number_like_test
WHERE CAST(num AS DECIMAL(12,6)) LIKE '%68%'
And here's a SQL Fiddle showing the rounding behavior: SQL Fiddle
It's probably because a FLOAT data type represents a floating point number which is an approximation of the number and should not be relied on for exact comparisons.
If you need to do a search that includes the float value you would need to either store it in a decimal data type (which will hold the exact number) or convert it to a varchar using something like the STR() function

how to convert different datatypes to int in sql

I have a nvarchar(200) column in a table that contains a mix of integers (as strings) and non-integer strings and symbols also. E.g. Some sample data :-
Excuse me for my typing in my initial post I mentioned varchar(200) but in fact it is 'nvarchar(200)'
02
0
.../
125
00125
/2009
1000
0002589
000.00125
Marathi numbers like & letters
how can I order this Column?
You can use CAST to convert a varchar to an INT given that varchar is holding a proper number.
SELECT CAST(varCharCol as Int)
E.g.
col1 as Varchar(10)
col1 = '100' converting to INT will be successufl
but if col1 = '100 xyz' will be unsucessful in the process.
Looking at your string you may have to use number of LTRIM, REPLACE to get hold of the digits or using a regex to get comma separated numbers. That too it's not very clear how your original string looks like.
References.
Many DBMS have CAST() functions where you can convert one datatype to another.
For MySQL have a look at this site
You can Use CAST and Convert to convert string type value to int type. but be sure the value should numeric.
select convert(int,'123')
select CAST('123' as int)
You can use this query
SELECT CASE
WHEN ISNUMERIC(colName)=1 THEN ROUND(colName, 0)
ELSE 0 END AS [colName]
FROM tblName