SQL cast from int to decimal

I have two columns in a table that are populated with integer values. For each record, I want to separate the values ​​of these two columns and format the output so that the decimal point is moved to the places on the right.

For example, if I have the values ​​of two columns for the same record as 4 and 1, and I want to divide 1 by 4 (so 1/4), then I want the result to be 25.00.

Here is the last thing I tried a little back:

CAST(Total AS Decimal(2))/CAST(TotalAnswers AS Decimal(2)) AS 'Percent' 

I was unable to find a syntactical explanation of the CAST function to see that I passed the parameter for the decimal representation. When I change it, it sometimes changes the number of places to the right of the decimal, but the results are not always expected, so I would like to help with this a little.

+8
casting sql sql-server-2005
source share
4 answers

Write this:

 SELECT CAST(CAST(Total As float) / TotalAnswers * 100 As decimal(8, 2)) 
+18
source share

DECIMAL(2) - decimal digit of two digits before and without digits after the decimal point. This does not allow you to have digits after the decimal point!

The DECIMAL(p,s) specification DECIMAL(p,s) defines the number of full digits ( p ) and the number of digits after the decimal point ( s ) (where s cannot be greater than p and equal to 0 if you skip).

You need to use something like DECIMAL(4,2) (only 4 digits from 2 after the decimal point, therefore: also 2 to the decimal point) or something like that - some digits before and some after the decimal point - then you see the desired result!

For more information about the DECIMAL type and its syntax, see "Email for MSDN Books" in decimal and numeric

+2
source share

In fact, there are a couple of parameters.

 (p, s) 

Where

  • p represents "precision" - the total number of digits before and after the decimal point.
  • s represents the "scale" - the number of digits after the decimal point.

By providing only one parameter, you give only accuracy.

See MDSN .

+2
source share

From an online book for decimal data: Numerical data types that have fixed precision and scale.

decimal [(p [, s])] and numeric [(p [, s])] Fixed accuracy and scale numbers. When maximum precision is used, valid values ​​range from -10 ^ 38 +1 to 10 ^ 38-1. The SQL-92 synonyms for decimal are dec and dec (p, s). a numeric value is functionally equivalent to decimal.

p (precision) The maximum total number of decimal digits that can be stored both to the left and to the right of the decimal point. Accuracy should be a value from 1 to a maximum accuracy of 38. The default accuracy is 18.

s (scale) The maximum number of decimal digits that can be stored to the right of the decimal point. The scale must be a value from 0 to p. Scale can only be specified if accuracy is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes depend on accuracy.

+1
source share

All Articles