10

How to convert an nvarchar to decimal in SQL Server?

I need to convert a value like '38,716.1311' to 38716.1311.

I have tried using this method but can't successfully convert:

DECLARE @TempValue NVARCHAR(100) = '38,716.1311'

SELECT 
    CONVERT(DECIMAL(18, 2), @TempValue) 

Can anyone suggest the correct query? Thanks in advance

1
  • 3
    How about removing the comma Commented Mar 1, 2017 at 9:30

7 Answers 7

15

Just remove comma from your string prior to conversion:

Select CONVERT(DECIMAL(18,2),replace('38,716.1311', ',', '')) 
6

Remove the comma by using REPLACE like so:

Declare @TempValue nvarchar = '38,716.1311'
Select CONVERT(DECIMAL(18,2), REPLACE(@TempValue, ',', ''))
4
Declare @TempValue nvarchar(100)
    SET @TempValue = Replace('38,716.1311',',','')
Select cast(@TempValue AS DECIMAL(18,2)) 

--we can not convert value Like "38,716.1311" (NVARCHAR) To DECIMAL so first we replace "," with blank "38716.1311" then convert with DECIMAL

1
  • Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how and why this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Commented Mar 1, 2017 at 12:24
4

Your nvarchar values are culture-specific. (Having culture-specific decimal and thousand separators) Hence you could use the PARSE method while passing in the proper culture.

DECLARE @TempValue NVARCHAR(100) = '38,716.1311'

SELECT PARSE(@TempValue AS DECIMAL(18, 4) USING 'en-US') 
2

Its better if the @TempValue is MONEY so it disregard the comma separated

Declare @TempValue MONEY =  '38,716.1311'
Select CAST(@TempValue AS DECIMAL(18,2))
0

Use MONEY data type and convert into decimal data type:

DECLARE @Col MONEY = '38,716.1311'
SELECT CONVERT(DECIMAL(20,4),@Col) 

OR Replace comma and convert into decimal

DECLARE @Col VARCHAR(100)  = '38,716.1311'
SELECT CONVERT(DECIMAL(20,4),REPLACE(@Col,',',''))
0

In my case for example some data like: version: '1.2.12'

I want to register like version: 1.212 in Sql

  1. Clean the varchar ( eliminate dot or commas )

  2. Cast to char (6 digit) and pad with 0 the empty spaces. (Catch null with coalesce)

  3. Cast to numeric and divide to 100000

  4. Cast to decimal (10,4)

Result ->> version 1.212

Select 'version'=cast(cast(replace(cast(replace(coalesce([##DATA##],'0'), '.', '') as char(6)),' ','0')as numeric(6))/100000 as decimal (10,4)

Maybe there is another solution which is more simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.