简体   繁体   中英

SQL Server ROUND not working

I have a table where one column is Price ( decimal(18,9) ) and another Volume ( bigint ).

I am multiplying both values and then applying round function but nothing works.

I want it to be 2 decimal place precision. How to do it?

SELECT 
    CAST((Price * Volume) AS decimal(38,2)) test1, 
    ROUND((Price * Volume), 2) 'VolumePrice',  
    CONVERT(DOUBLE PRECISION, (Price * Volume)) 'test2' 
FROM a

Table values are something like this:

    Price           Volume
    -------------------------
    63.380000000    131729
    63.380000000     61177
    44.860000000    246475
    44.860000000    246475
    44.860000000     63937
    97.990000000     84620
    191.650000000   438821

I want to simply multiply the price by the volume, to get a total value amount.

ROUND() just changes the decimal value up or down, doesn't change the data type precision.

What you want is to convert to DECIMAL with a scale of 2.

SELECT 
    CONVERT(DECIMAL(18,2), Price * Volume) AS DecimalConversion
FROM 
    A

Converting a decimal of higher scale ( Price * Volume ) to a lower one will automatically round the last digit:

SELECT 
    CONVERT(DECIMAL(18,2), '1.901999'), -- 1.90
    CONVERT(DECIMAL(18,2), '1.909999'), -- 1.91
    CONVERT(DECIMAL(18,2), '1.905999'), -- 1.91
    CONVERT(DECIMAL(18,2), '1.904999')  -- 1.90

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence

source : MSDN docs

In SQL Server precedence order for data types in question is :

  1. decimal
  2. bigint

So bigint is converted to implicitly converted to decimal.

If you need your desired results you should simply do

SELECT 
VolumePrice= cast(Price * Volume as decimal(18,2) ) 
FROM a

See working demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM