简体   繁体   中英

Round SQL Server

how do I evit avoid rounding in SQL Server

DECLARE @NUMERO1 AS numeric(26,8) = 0
DECLARE @NUMERO2 AS numeric(26,8) = 0

SET @NUMERO1 = 1.92306964
SET @NUMERO2 = 105
SELECT 1.92306964 * @NUMERO2
SELECT @NUMERO1* @NUMERO2 

Is not the same result.

Thanks

If you want better precision, use FLOAT rather than NUMERIC/DECIMAL types. Try the following instead:

DECLARE @NUMERO1 AS FLOAT = 1.92306964
DECLARE @NUMERO2 AS FLOAT = 105
SELECT 1.92306964 * @NUMERO2 -- 201.9223122
SELECT @NUMERO1 * @NUMERO2  -- 201.9223122

When you hard code a number like that in SSMS it gets treated as a float, not numeric, which behaves differently. To make the output of your two select statements match, you would need to write something like this:

DECLARE @NUMERO1 AS numeric(26,8) = 0
DECLARE @NUMERO2 AS numeric(26,8) = 0

SET @NUMERO1 = 1.92306964
SET @NUMERO2 = 105
SELECT cast(1.92306964 as numeric(26,8)) * @NUMERO2
SELECT @NUMERO1* @NUMERO2

However, I assume you want the greater precision of float that will let you work backwards like such:

DECLARE @NUMERO1 AS float = 0
DECLARE @NUMERO2 AS float = 0

SET @NUMERO1 = 1.92306964
SET @NUMERO2 = 105
SELECT 1.92306964 * @NUMERO2
SELECT @NUMERO1 * @NUMERO2 
SELECT (1.92306964 * @NUMERO2) / 1.92306964 -- returns @NUMERO2 as expected
SELECT (@NUMERO1 * @NUMERO2) / @NUMERO1 -- returns @NUMERO2 as expected

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