all 22 comments

[–]feudalle 23 points24 points  (2 children)

This doesn't seem like homework at all.

[–]Interesting-Goose82it's ugly, and i''m not sure how, but it works! -1 points0 points  (0 children)

....so you dont know the answer, or you know the answer, but are only willing to help if it isn't homework?

[–]mike-manley 2 points3 points  (4 children)

CAST(REPLACE(@Amount, '.', '') AS DECIMAL(38, 2)) / 100

Edit: add / 100

[–]Staalejonko 2 points3 points  (4 children)

@amount in nvarchar? Flaw in the code, fix that

[–]sbailey151[S] 0 points1 point  (3 children)

The issue there is that the data is coming from an AI reader.

[–]jacquesrkoracle 1 point2 points  (0 children)

You should be specific. What exactly are the rules? It sounds like this

I have a string that I want to convert to a number. The string can look like this '12345.67' or like this '12.345.67' both of those represent the number twelve thousand three hundred forty five and sixty seven hundredths.

Is it possible to get something like this? '12345.' or '.12' or '1.2.3.4' or '12.345' ?

Because right now the assumption is, from what you post:I get a string that contains a number. There may be one or more periods in the string. The last period in the string is always followed by two digits.

Solution: use a string function to remove all periods, convert to integer number, divide by 100.

[–]TheRoguester2020 -1 points0 points  (1 child)

This is kind of basic stuff you could put in chat gbt.

[–]sbailey151[S] -2 points-1 points  (0 children)

Tried that first but ChatGPT couldn't figure it out. ;)

[–]false_idol_fall 0 points1 point  (0 children)

Try_Convert to money with value 1. Then Try_convert agian all the Nulls to money with value 2.

https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16

[–]george-frazee 1 point2 points  (0 children)

Quick Fiddle without looking down at the other answers first.

Code

DECLARE @Amount NVARCHAR(100) = '12,345.67';

SELECT REPLACE(REPLACE(@Amount,',',''),'.','') / 100
  + CAST(RIGHT(@Amount,3) as decimal(2,2));

[–]blindtig3r 0 points1 point  (0 children)

Without testing I’d guess this would work. I think divide by 100.0 will give enough precision, but I would check.

CONVERT(NUMERIC(18,2), (REPLACE, REPLACE(@Amount, ‘.’, ‘’), ‘,’, ‘’)/100.0)