# Convert from varchar to decimal

hi all

i have a field which is stored as a varchar(30). I need it as varchar as the value can be characters or numbers etc.

in some case i  need to add two of these fields when the text value are deciamls e.g. '.75' to do this i need to change them to decimals first. i have tried Cast('0.75' as DECIMAL(28,9)) but it gives me 1.00000000. it seems to be rounding to the nearest whole number. can anyone help?
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Software Designer, SysDBA, WebMaster OwnerCommented:
declare @aNumber DECIMAL(28,9)

set @aNumber =  Cast('0.759' as DECIMAL(28,9))

SELECT @aNumber

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
What SurferJoe posted should work.  You shouldn't issue Cast('0.75' as DECIMAL(28,9)) and get 1.000000 unless there is some other conversion going on.  Post your SELECT statement, and we can help determine that.

But from what you've mentioned, I think you need a more robust solution.  For example, if you have 2 fields in a table, and you want to return the sum of those fields if they are numeric, then try something like this:

SELECT Value = CASE
WHEN ISNUMERIC(Field1) = 1 THEN CAST(Field1 AS DECIMAL(28,9))
ELSE 0 END
+
CASE WHEN ISNUMERIC(Field2) = 1 THEN CAST(Field2 AS DECIMAL(28,9))
ELSE 0 END
FROM Table

(Where Field1 and Field2 are your VARCHAR fields and Table is your table)
Author Commented:

Thanks SurferJoe that worked!

Thanks as well  Dexstar! i had implemented the other answer before i saw urs :-( as you poined out another field in the statment had an incorrect conversion!

Thanks again
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.