Syntax error when nesting STR inside custom formatting? - sql

I'm trying to convert a number to a string with STR, and give it custom number formatting.
Currently, I tried to nest the two:
DECLARE
#Num float
SET
#Num = 222.33339
SELECT
FORMAT(STR(#Num,(8), 4), #,##0.00)
/*String(Original Number, Total Length of Number, Length of Decimal Places)*/
FROM
Sample
But I am receiving a syntax error in my Format function. I've tried debugging but I feel like I'm missing something obvious. Any suggestions?

Change your Format function to be:
SELECT FORMAT(#Num, N'#,##0.00')

Related

Roundoff error in sql

DECLARE #TAX VARCHAR(30)=120.45
DECLARE #TaxRoundOf VARCHAR(30)
SET #TaxRoundOf=ROUND(#TAX,1)
SELECT #TaxRoundOf
This Gives Result (#TaxRoundOf=120.5)
DECLARE #TAX VARCHAR(30)=146.45
DECLARE #TaxRoundOf VARCHAR(30)
SET #TaxRoundOf=ROUND(#TAX,1)
SELECT #TaxRoundOf
This Gives Result (#TaxRoundOf=146.4)
But I need to return 146.50 . why this mismatch between two results?
any one can help plz?
Since you are using VARCHAR to store your numbers, SQL Server is having to do implicit conversion to float behind the scenes, which is having knock on effects on your calculations. You can reproduce this using the below query:
SELECT ROUND(CONVERT(FLOAT, 120.45),1), -- 120.5
ROUND(CONVERT(FLOAT, 146.45),1), -- 146.4
ROUND(CONVERT(DECIMAL(10, 2), 120.45),1), -- 120.50
ROUND(CONVERT(DECIMAL(10, 2), 146.45),1) -- 146.50
Since floating point numbers are not exact, 146.45 cannot be exactly represented as a float, and ends up being stored as a very slightly smaller number, so when this is passed to the round function, it is rounded down, instead of up.
The solution, as demonstrated by the 3rd and 4th columns in the above query, is to use a more precise data type.
You can use this:
SET #TaxRoundOf=ROUND(10 * CAST(#TAX AS FLOAT)) / 10
instead of:
SET #TaxRoundOf=ROUND(#TAX,1)
DEMO
PS as #GarethD already mentioned I wouldn't use #TAX as VARCHAR type.
You can also rely on numeric rounding instead of converting your string to a float, which can lose information.
Cast a string to numeric and then round:
select round(cast('146.45' as numeric(18,2)), 1)
-- 146.50
A decimal constant is already a decimal so there's no need to cast it:
select round(146.45, 1)
-- 146.50

T-SQL - CAST char with leading zeros to int

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 :)

Trying to Find Maximum Value

I'm trying to find a maximum number of a string. First I try to turn it into an Integer field first, but keep getting error message for example:
Conversion failed when converting the nvarchar value '3,029' to data type int.
I tried to replace the possible single quotation marks into a blank char like below:
SELECT TOP 100 (CAST(REPLACE(a.PortNumber,'''','') AS INT)) FROM dbo.Account a
WHERE nwp_AccountType = 121710000
ORDER BY (CAST(REPLACE(a.PortNumber,'''','') AS INT)) DESC
But still getting the same error message again.
Any idea?
The error is in your REPLACE statement
(CAST(REPLACE(a.PortNumber,',','') AS INT))
The problem was the comma, I added another replace for the comma to an empty string and it works.

Sybase convert issue from float to varchar

First, I need to mention that my current sybase db version is Adaptive Server Enterprise 12.5.4. I aim to convert float data type into varchar via sybase convert function in order to concat several of these kinds of variables, format and store in string type.
Unfortunately, it is not the case. Simply using convert(varchar(20), float_var) or cast() function cannot correctly return the precise value.
For example, ...
declare #float_var float
begin
select #float_var =345.1237 --from table actually
select convert(varchar(20),#float_var) --return 345.1236999999
end
The incorrect string results returned occasionally have 99999 or 00001 suffix.
I tried many function including specify the precision, but there are still several cases not working on it. The sybase internal function does not exactly work on it.
I suppose this is a gerneral issue while using Sybase DB, however few answer found in serach. During my past experience, Sybase store procedure gammer always has sort of tolerance in runtime and internal fix when error encounter. This issue make me confused how Sybase works internally. Any advice would be appreciated, thanks in advance.
there are a couple of possible solutions for this.
firstly, let's try to convert the float to decimal first, then to varchar.
select cast(cast(#float_var as decimal(13,4)) as varchar)
alternatively, and this is where my ASE memory might fail me a little, would be to use the STR function like so:
Select ltrim(str(#float_var, 25, 5))
You have to TRIM the output as the STR function padding empty spaces on to the left of the result
this works for me:
declare #float_var float
begin
select #float_var = 96.332
select cast(cast(#float_var as decimal(13,4)) as varchar) -- Returns 96.3320
end
declare #float_var float
begin
select #float_var = 345.1237
select cast(cast(#float_var as decimal(13,4)) as varchar) -- Returns 345.1237
end

SQL Convert float to comma varchar with decimals

I have a couple floats that are kinda big. They're around a 100 million.
I would like this number to show like the following 123,456,789.01234
I've found that I can use CONVERT if its a money datatype but this doesn't do the full trick (it leaves off some decimal places).
I have to have commas on the left and five decimal places on the right.
Is there any built in SQL function to help with this? Or do I have to write a custom function?
Thanks
*** Update
I forgot to mention that I'm just displaying these as varchars. So there isn't any calculations after this.
This is running on an SQL database so MySQL and Oracle won't work.
DECLARE #f FLOAT
SET #f = 123456789.01234
SELECT LEFT('$' + CONVERT(VARCHAR(20), CAST(#f AS MONEY), 1), LEN(#f) - 2)
this will cut it up to two places of decimal for formatting. You can change LEN(#f) - 2 to modify this setting.
if you are just displaying this as text you can do the following:
oracle :
select to_char(123456789.01234,'999,999,999.99999') from dual; => 123,456,789.01234
MySQL :
select format(123456789.01234,5) => 123,456,789.01234<br>
the MySQL function rounds