I have a requirement to convert fields in float
to string
, with following restrictions
For example:
I have tried the following, but fail for some of the above requirements and also not able to remove the zero's.
select
CASE WHEN RIGHT(convert(VARCHAR, cast(cast(product_price as DECIMAL(28,6)) as float)),2) = ".0"
THEN LEFT(convert(VARCHAR, product_price),(CHAR_LENGTH(convert(VARCHAR(15), product_price))-2))
ELSE substring( convert(VARCHAR, cast(cast(product_price as DECIMAL(28,7)) as float)),1, charindex(".",convert(VARCHAR, cast(cast(product_price as DECIMAL(28,7)) as float)))+6) END
from #TEMP
id | product_price
-------------------
1 | 17.3435302323
2 | 17.700000000
3 | 17.60
4 | 19.0
I guess, I have complicated the query and a simpler version should exists.
I know this could be easily handled in high level language, but if this could be easily be accommodated in the query itself then please let me know.
I'm not sure if there is easier way to do that on sybase.
This example works for me
declare @val float
declare @val2 float
select @val = 17.666655942234
select @val2 = 17.66
select substring(convert(varchar(30),@val), 1, patindex('%.%',convert(varchar(30),@val)))+reverse(convert(varchar(30),convert(int,reverse(substring(convert(varchar(30),@val), patindex('%.%',convert(varchar(30),@val))+1,6))))) as Val,
substring(convert(varchar(30),@val2), 1, patindex('%.%',convert(varchar(30),@val2)))+reverse(convert(varchar(30),convert(int,reverse(substring(convert(varchar(30),@val2), patindex('%.%',convert(varchar(30),@val2))+1,6))))) as Val2
solution with varchar(15)
declare @val numeric(10,5)
declare @val2 numeric(10,5)
select @val = convert(numeric(10,5),17.666655942234)
select @val2 = convert(numeric(10,5),17.66)
select convert(varchar(15),substring(convert(varchar(15),@val), 1, patindex('%.%',convert(varchar(15),@val)))+reverse(convert(varchar(15),convert(int,reverse(substring(convert(varchar(15),@val), patindex('%.%',convert(varchar(15),@val))+1,6)))))) as Val,
convert(varchar(15),substring(convert(varchar(15),@val2), 1, patindex('%.%',convert(varchar(15),@val2)))+reverse(convert(varchar(15),convert(int,reverse(substring(convert(varchar(15),@val2), patindex('%.%',convert(varchar(15),@val2))+1,6)))))) as Val2