Convert Integers to Floats in MySQL

In MySQL, you can convert integers to floats by using the CAST() or CONVERT() functions, specifying a float or decimal data type.

In this tutorial, you will learn how to use CAST() and CONVERT() to convert integers to floats, allowing for decimal representation in your queries.

Converting Integers to Floats with CAST and CONVERT

Both CAST() and CONVERT() functions allow you to change integers to floats by specifying the desired data type. This is useful when performing calculations that require decimal precision.

Examples: Converting Integers to Floats

Here, we’ll explore several examples that show how to convert integer values directly to floats, without needing a table.


1. Using CAST() to Convert Integers to Floats

To convert an integer like 100 to a float using CAST():

</>
Copy
SELECT CAST(100 AS DECIMAL(10, 2)) AS float_value;

This query returns 100.00 as a decimal with two decimal places, using CAST() to convert the integer into a float format.

Convert Integers to Floats in MySQL - Example: convert 100 to decimal with base 10 and precision 2

2. Using CONVERT() to Convert Integers to Floats

To convert an integer, such as 250, to a float with CONVERT():

</>
Copy
SELECT CONVERT(250, DECIMAL(10, 5)) AS float_value;

This query returns 250.00000 in a float format by converting the integer to a decimal with five decimal places using CONVERT().

Convert Integers to Floats in MySQL - Example: CONVERT 250 to DECIMAL with base 10 and precision 5

3. Converting Column Values from Integer to Float

If you have a column of integers, like a price field in a products table, you can convert these to float values:

</>
Copy
SELECT price, CAST(price AS DECIMAL(10, 2)) AS float_price
FROM products;

This query selects each integer price and converts it to a float format with two decimal places.


Using Division for Implicit Float Conversion

In MySQL, dividing an integer by a float (or another integer with decimal places) automatically converts the result to a float. For instance:

</>
Copy
SELECT 100 / 3 AS implicit_float_conversion;

This query returns 33.3333..., as MySQL performs implicit conversion to produce a float result.

Convert Integers to Floats in MySQL - Example: Using Division for Implicit Float Conversion