Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Varchar to Double in sql?

Tags:

I have problem with my query when I was trying to convert the varchar field to double (numeric). I have this sql statement:

SELECT fullName, CAST(totalBal as numeric(9,2) FROM client_info ORDER BY totalBal DESC 

Actually I want to display the values of totalBal in descending order. But since that field is in varchar, the resultset is sometimes wrong. This is the resultset when I tried to query using this statement:

SELECT fullName, totalBal FROM client_info ORDER BY totalBal DESC  

Resultset is:

enter image description here

The sorting of totalBal is not correct. So I decided to convert the varchar to numeric so that it might be sorted perfectly. Any idea?

like image 303
Jay Marz Avatar asked Jan 24 '13 07:01

Jay Marz


People also ask

What is cast () and convert () functions in SQL Server?

The cast and convert functions provide similar functionality. They are used to convert a value from one data type to another. So let's take a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

How do I convert VARCHAR to numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.

What is cast as double?

In theatrical terms, double-casting is when two actors are both cast in the same role, and take turns playing the role during alternating performances. It is different than casting an understudy. An understudy only performs when the actor in the role is away or ill.

Can we convert VARCHAR to int in SQL?

The examples below shows the conversion of a string to the int type. A varchar variable and an int variable are declared, then the value of the varchar variable is set. It converts varchar to int type with the help of cast and convert functions. The varchar variable must contain numeric characters.


2 Answers

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName,         CAST(totalBal as DECIMAL(9,2)) _totalBal FROM client_info  ORDER BY _totalBal DESC 
like image 170
John Woo Avatar answered Nov 15 '22 18:11

John Woo


This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC 
like image 35
Hammad Khan Avatar answered Nov 15 '22 19:11

Hammad Khan