Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 - conversion from string to int fails

Don't know why this conversion fails.

SELECT CAST('32.999' AS INT)

throws the error saying

Conversion failed when converting the varchar value '32.000' to data type int.

I know I can convert it to Decimal and then convert it to Int but why 32.000 is not being converted to Int directly?

Am I missing something here?

--EDIT--

I don't care about the decimal points. I want SQL to ignore them.

like image 586
Asdfg Avatar asked Jul 15 '26 19:07

Asdfg


2 Answers

32.000 can not be represented accurately as an int due to the decimal places. Instead, if you want a numeric value with decimals, you can use a float (or numeric) data type.

Select CAST('32.000' as float)

edit: misread your question a little bit.

I'm assuming SQL is trying it's best to preserve your intentions. When it reads in that the numeric value you're attempting to cast has decimal values, it will flat out reject it.

like image 66
Zhais Avatar answered Jul 17 '26 16:07

Zhais


used SELECT CAST(ROUND('32.999',0,1) AS INT) and it works well.

like image 35
Asdfg Avatar answered Jul 17 '26 16:07

Asdfg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!