Link to home
Start Free TrialLog in
Avatar of lm1189
lm1189

asked on

Float Rounding when converted to varchar

When converting a value from a Float to a varchar, it's rounding.  For example, I have a value, $35140.08, and when converted to a varchar it becomes 35140.1.  My ultimate goal is I need to present the value (which is a float datatype) with 2 decimal places with no decimal point, ie: 3514008.

SELECT REPLACE(CAST(CAST('35140.08' as FLOAT) as VARCHAR(255)),'.','') as MyValue

Open in new window


Any ideas?  I tried FLOOR, STR and neither helped.
Avatar of Lee
Lee
Flag of United Kingdom of Great Britain and Northern Ireland image

SELECT REPLACE(CAST(CAST('35140.08' as numeric (24, 2)) as VARCHAR(255)),'.','') as MyValue
declare @f as float
set @f = 35140.088888888888

SELECT CAST(CAST(@f * 100 as bigint) as VARCHAR(255)) as MyValue
Like it...

Even simpler:

SELECT cast(35140.08 * 100 as bigint)
:) I like simple
What if the value internally is: $35140.086?

Do you want to see 3514008 or 3514009?
When converting a value from a Float to a varchar, it's rounding.
Just as an aside and I am sure you have already figured this out, but float is an approximate numeric value and typically should not be used in business applications.  Instead you should use numeric or money as they are fixed numeric types and therefore no rounding problems like this.
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
lm1189, Hi. Have we answered this question - could it be closed off?
Avatar of lm1189
lm1189

ASKER

I tried multiple methods but all had rounding issues, I eventually had to conver to the Money datatype which resolved my issues.