问题
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