x
Solved

# convert int to decimal in sql

Posted on 2009-05-11
Medium Priority
1,709 Views
I have a int column with a value of 3250. I need to return a 32.50 value. How do I do this? whatever I tried seems to illeminates the 50.
0
Question by:sleiman

LVL 6

Expert Comment

ID: 24361879
something like this ??

select  my_field = (convert(float, 3250)) / 100
0

LVL 6

Expert Comment

ID: 24361930
Replace columnname and tablename accordingly in the attached code snippet

``````Select (convert(float,columnname))/100) AS ReturnResult from tablename
``````
0

LVL 9

Expert Comment

ID: 24362405
I'm more of a C#/C++ buff, but I'll give this a shot.

The way I'd do this in a programming language is convert the number to a String, and insert a decimal two places to the left of the end of it. That way, there's no risk of any loss of precission at all, and it makes things much simpler ;). I'll try and code it out, though my SQL is not top-notch. If this doesn't work for you, let me know, as the syntax varies from engine to engine.

SELECT (SUBSTRING(column, 0, LEN(column) + "." + SUBSTRING(column, LEN(column) - 2) AS Result FROM tblTableName;

I can't remember if Strings in SQL are 0-based or 1-based--if they're not 0-based, it should be a pretty easy fix, though ;)
0

LVL 41

Accepted Solution

ID: 24365122
Never convert to float. Float know as aproximate data type. Approximate numeric data types do not store the exact values specified for many numbers. It will give you wrong results most of the time. Use decimal instead. Check this out:
Select cast(columnname as decimal)/100.00 as yourresult from yourtable

http://msdn.microsoft.com/en-us/library/ms187912.aspx
0

Author Comment

ID: 24365357
Using the float conversion did not return the result that I needed.

(convert(float, 3250)) / 100  returns 32.0 and I need to get 32.50

(cast(3250 as decimal)/100.00) returns 32.50000

Final solution:
cast(columnname/100.00 as decimal(10,2)) return 32.50
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.