SQL Server: Convert varchar to decimal (with considering exponential notation as well)

爷,独闯天下 提交于 2020-06-25 17:27:23

问题


I need to convert data of a table and do some manipulation.

One of the column datatypes is Varchar, but it stores decimal numbers. I am struggling to convert the varchar into decimal.

I have tried CAST( @TempPercent1 AS DECIMAL(28, 16))

Problem is that data also has some values in exponential notation, for example: 1.61022e-016.

The sql query is throwing error on encountering such value. The error is Error converting data type varchar to numeric.

How should I handle exponential notation values during varchar to decimal conversion?


回答1:


You may try following, but you may loose accuracy:

select cast(cast('1.61022e-016' AS float) as DECIMAL(28, 16))



回答2:


You could just do

CAST(CAST(value AS float) AS decimal(36, 20))

but...

If you do that, the cast-to-float will also change all values that have no E inside - because floats can only be as exact as the machine-epsilon ...

You can mitigate that, by only casting to float if the number contains an E (+/-).
If it's a normal decimal number, just cast to decimal directly.
This will minimize float-round-off errors.

SELECT 
    CASE 
        WHEN factor LIKE '%E-%' THEN CAST(CAST(factor AS FLOAT) AS DECIMAL(36, 20)) 
        WHEN factor LIKE '%E+%' THEN CAST(CAST(factor AS FLOAT) AS DECIMAL(36, 20)) 
        ELSE CAST(factor AS DECIMAL(36, 20)) 
    END AS factor
FROM T_IFC_Import_Currency 

Or more compact:

SELECT 
    CASE 
        WHEN factor LIKE '%E[+-]%' THEN CAST(CAST(factor AS FLOAT) AS DECIMAL(36, 20)) 
        ELSE CAST(factor AS DECIMAL(36, 20)) 
    END AS factor
FROM T_IFC_Import_Currency 


Note:
Don't simplify this to:

SELECT
    CAST
    (
        CASE 
            WHEN factor LIKE '%E[+-]%' THEN CAST(factor AS FLOAT) 
            ELSE factor 
        END
        AS decimal(36,20) 
    ) AS factor 
FROM T_IFC_Import_Currency 

because that means the case expression is first implicitly cast to float before it is being cast to decimal...




回答3:


select convert(Decimal(28,16),convert(float,'1.61022e-016'))


来源:https://stackoverflow.com/questions/18452569/sql-server-convert-varchar-to-decimal-with-considering-exponential-notation-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!