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

Related

Extract String Between Two Different Characters

I am having some trouble trying to figure out a way to extract a string between two different characters. My issue here is that the column (CONFIG_ID) contains more that 75,000 rows and the format is not consistent, so I cannot figure out a way to get the numbers between E and B.
*CONFIG_ID*
6E15B1P
999E999B1P
1E3B1P
1E30B1P
5E24B1P
23E6B1P
Another option is to use a CROSS APPLY to calculate the values only once. Another nice thing about CROSS APPLY is that you can stack calculations and use them in the top SELECT
Notice the nullif() rather than throwing an error if the character is not found, it will return a NULL
THIS ALSO ASSUMES there are no LEADING B's
Example
Declare #YourTable Table ([CONFIG_ID] varchar(50)) Insert Into #YourTable Values
('6E15B1P')
,('999E999B1P')
,('1E3B1P')
,('1E30B1P')
,('5E24B1P')
,('23E6B1P')
,('23E6ZZZ') -- Notice No B
Select [CONFIG_ID]
,NewValue = substring([CONFIG_ID],P1,P2-P1)
From #YourTable
Cross Apply ( values (nullif(charindex('E',[CONFIG_ID]),0)+1
,nullif(charindex('B',[CONFIG_ID]),0)
) )B(P1,P2)
Results
CONFIG_ID NewValue
6E15B1P 15
999E999B1P 999
1E3B1P 3
1E30B1P 30
5E24B1P 24
23E6B1P 6
23E6ZZZ NULL -- Notice No B
SUBSTRING(config_id,PATINDEX('%E%',config_id)+1,PATINDEX('%B%',config_id)-PATINDEX('%E%',config_id)-1)
As in:
WITH dat
AS
(
SELECT config_id
FROM (VALUES ('1E30B1P')) t(config_id)
)
SELECT SUBSTRING(config_id,PATINDEX('%E%',config_id)+1,PATINDEX('%B%',config_id)-PATINDEX('%E%',config_id)-1)
FROM dat
A cased substring of a left could be enough.
select *
, CASE
WHEN [CONFIG_ID] LIKE '%E%B%'
THEN SUBSTRING(LEFT([CONFIG_ID], CHARINDEX('B',[CONFIG_ID],CHARINDEX('E',[CONFIG_ID]))),
CHARINDEX('E',[CONFIG_ID]), LEN([CONFIG_ID]))
END AS [CONFIG_EB]
from Your_Table
CONFIG_ID
CONFIG_EB
6E15B1P
E15B
999E999B1P
E999B
1E3B1P
E3B
1E30B1P
E30B
5E24B1P
E24B
23E6B1P
E6B
23E678
null
236789
null
23B456
null
Test on db<>fiddle here

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

SQL SUM without rounding

I have the following query that gives a rounded result. How can I modify this to
Stop rounding
Display to 2 decimal places. E.g 3.456 -> 3.45
SELECT SUM(Invoice_Details.Amount) AS TotalNet_C FROM Invoice_Details WHERE Invoice_Details.Invoice_Number = ||InvNo||
To format it to 2 digits you can e.g. convert it to currency.
SELECT CAST(SUM(Invoice_Details.Amount) AS money) AS TotalNet_C
FROM Invoice_Details
WHERE Invoice_Details.Invoice_Number = ||InvNo||
For be more specific you can use CONVERT.
Check this for details: http://msdn.microsoft.com/de-de/library/ms187928.aspx
About rounding: You want to crop the digits, not round them:
SELECT CAST(CAST(3.456 * 100 AS int) as float)/100
This will do it. Your case then
SELECT CAST(CAST(CAST(SUM(Invoice_Details.Amount) * 100 AS int) as float)/100 AS money) AS TotalNet_C
FROM Invoice_Details
WHERE Invoice_Details.Invoice_Number = ||InvNo||
you can simply do this for rounding your value
Str(ColumnName, 10, 2)
10-- this is for total length of your value.
2-- this is for how many decimal you want
declare #Num decimal(6,3)
set #Num = 3.456
select LEFT(round(#Num, 2, 1),4)
OR
select CAST(round(#Num, 2, 1)AS MONEY)
I think u should to convert value before sum_function and u can use parameters of the numeric/decimal, just like this:
select SUM(TRY_CONVERT(decimal(18,2), value) from TestTable ...

SQL Search a Numeric Field for non whole numbers

I have a DB that has a numeric field and I need to search all the rows and return only the non whole numbers.
I have tried the query below and it keeps retuning records that have 0.
SELECT
li.QTY
FROM
TABLE LI
WHERE
li.QTY like '%.%'
You can use LIKE only with char fields, not with number (integer or float) ones.
If by "whole numbers" you mean 0.0 , 2.0 , -5.0 , etc. and not 12.5 , 0.67 then this can do:
SELECT li.QTY
FROM TABLE LI
WHERE li.QTY != ROUND(li.QTY , 0)
;
(for SQL-Server: edited the TRUNC into ROUND)
You could also use the FLOOR or CEILING functions:
SELECT li.QTY
FROM TABLE LI
WHERE li.QTY != FLOOR(li.QTY)
;
Why it does not work. When QTY is a numeric column, when you display it, or implicitly convert to varchar (LIKE does it implicitly), ALL numbers will be cast to the same number of decimal places.
Consider this SQL statement
with TBL(qty) as (select 1.1 union all select 3)
SELECT li.QTY FROM TBL LI WHERE li.QTY like '%.%'
Output
1.1
3.0 << this contains "." even if it does not need to
Cast it to a bigint and it will drop any decimals, then compare it again.
SELECT li.QTY FROM TBL LI
WHERE li.QTY <> CAST(qty as bigint)
If you MUST use LIKE (or just for show..)
SELECT li.QTY, CONVERT(varchar, li.qty)
FROM TBL LI
WHERE li.QTY LIKE '%.%[^0]%'
--Most Def...Cast as an int...Save you from validation of anything. Especially for conversions of dates into a whole date since Microsoft does not like a round down date function.
--For example:
--For every 300 hours an employee works they receive 1 whole day of vacation
--partial days of vacation will not be counted
Declare
#SumHours as decimal(38,10),
#VacationValidation as int
Set #SumHours = 3121.30000000000000000000
Set #VacationValidation = 300
Select cast(((#SumHours)/(#VacationValidation)) as int)
Select day(((#SumHours)/(#VacationValidation))) -1
--without casting as an int, I would need to validated the Day function to make sure that I'm not
--offsetting a whole day by one day.
CAST function work for me.
SELECT li.QTY FROM TABLE LI WHERE li.QTY != CAST(li.QTY AS INTEGER)
DECLARE #Value AS float
SET #Value = 250.00
CASE WHEN CHARINDEX('.',(CAST(b.Value/#Value as char))) = 0 THEN 'WholeNumber' ELSE 'Fraction' END AS mResult

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)