2

i have the next problem, i have a table with a string column, but i need convert this column in decimal or float. I tried with cast and convert but doesn't work example

input

3.50
7.10
18.50
27.00
46.50
46.90
117.90
226.70
274.70
Not available
Not available

tried

select cast(price as decimal(16,2)) from products

output

0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00

i see this warnings

Warning: #1918 Encountered illegal value '' when converting to DECIMAL

Warning: # 1292 Wrong truncated DECIMAL value:

I need later multiplier this column with another column

1
  • Just add 0; not cast or convert is needed. Even adding 0 may not be necessary if you use the string in a numeric context. Do you also need TRIM()? Commented Aug 22, 2020 at 5:03

3 Answers 3

3

If you add simple a 0 to the value you get a float or decimal which you can cast or usde directly everythin that is not a number is cobverteed to 0, but you can Replace Not available with another number

CREATE TABLE textvalue
    (`Input` varchar(13))
;
    
INSERT INTO textvalue
    (`Input`)
VALUES
    ('3.50'),
    ('7.10'),
    ('18.50'),
    ('27.00'),
    ('46.50'),
    ('46.90'),
    ('117.90'),
    ('226.70'),
    ('274.70'),
    ('Not available'),
    ('Not available')
;
SELECT CAST(Input + 0 AS DECIMAL(12,2))FROM textvalue
| CAST(Input + 0 AS DECIMAL(12,2)) |
| -------------------------------: |
|                             3.50 |
|                             7.10 |
|                            18.50 |
|                            27.00 |
|                            46.50 |
|                            46.90 |
|                           117.90 |
|                           226.70 |
|                           274.70 |
|                             0.00 |
|                             0.00 |

db<>fiddle here

Sign up to request clarification or add additional context in comments.

1 Comment

This was the only suggestion that worked when the column contained some empty/null/blank rows!
2

Try

select convert(price, decimal(16,2)) from products

Comments

0

See also the FORMAT function:

mysql> SELECT FORMAT('7.10', 2);
+-------------------+
| FORMAT('7.10', 2) |
+-------------------+
| 7.10              |
+-------------------+
1 row in set (0.00 sec)

mysql> SELECT FORMAT('1234567.10', 2);
+-------------------------+
| FORMAT('1234567.10', 2) |
+-------------------------+
| 1,234,567.10            |
+-------------------------+
1 row in set (0.00 sec)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.