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.
lm1189Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
PortletPaulConnect With a Mentor freelancerCommented:
[float]>>should not be used in business applications
I think it's actually forbidden in some places by regulation (but law is not my strong suit)
0
 
Lee SavidgeCommented:
SELECT REPLACE(CAST(CAST('35140.08' as numeric (24, 2)) as VARCHAR(255)),'.','') as MyValue
0
 
PortletPaulfreelancerCommented:
declare @f as float
set @f = 35140.088888888888

SELECT CAST(CAST(@f * 100 as bigint) as VARCHAR(255)) as MyValue
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Lee SavidgeCommented:
Like it...

Even simpler:

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

Do you want to see 3514008 or 3514009?
0
 
Anthony PerkinsCommented:
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.
0
 
PortletPaulfreelancerCommented:
lm1189, Hi. Have we answered this question - could it be closed off?
0
 
lm1189Author Commented:
I tried multiple methods but all had rounding issues, I eventually had to conver to the Money datatype which resolved my issues.
0
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.

All Courses

From novice to tech pro — start learning today.