Search code examples
sqlsybasetype-conversion

Sybase convert float to string


I have a requirement to convert fields in float to string, with following restrictions

  1. Need to truncate the results after 6 places after decimal point
  2. Truncate any trailing zeros after decimal

For example:

  1. 17.666655942234 ==> converted to string "17.666655"
  2. 17.6 ==> converted to string "17.6" and not "17.600000"
  3. 17.66 ==> converted to string "17.66"

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

#TEMP data

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.


Solution

  • 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