CAST to DECIMAL in MySQL

后端 未结 5 574
甜味超标
甜味超标 2020-12-23 12:08

I am trying to cast to Decimal in MySQL like this:

CAST((COUNT(*) * 1.5) AS DECIMAL(2))

I\'m trying to convert the number of rows in a tabl

相关标签:
5条回答
  • 2020-12-23 12:13

    MySQL casts to Decimal:

    Cast bare integer to decimal:

    select cast(9 as decimal(4,2));       //prints 9.00
    

    Cast Integers 8/5 to decimal:

    select cast(8/5 as decimal(11,4));    //prints 1.6000
    

    Cast string to decimal:

    select cast(".885" as decimal(11,3));   //prints 0.885
    

    Cast two int variables into a decimal

    mysql> select 5 into @myvar1;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select 8 into @myvar2;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select @myvar1/@myvar2;   //prints 0.6250
    

    Cast decimal back to string:

    select cast(1.552 as char(10));   //shows "1.552"
    
    0 讨论(0)
  • 2020-12-23 12:13

    If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

    This is the calculate:

    =(9/1147)*100

    SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);

    0 讨论(0)
  • 2020-12-23 12:14

    An alternative, I think for your purpose, is to use the round() function:

    select round((10 * 1.5),2) // prints 15.00
    

    You can try it here:

    0 讨论(0)
  • 2020-12-23 12:21

    From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:

    In standard SQL, the syntax DECIMAL(M) is equivalent to DECIMAL(M,0)

    So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:

    CAST((COUNT(*) * 1.5) AS DECIMAL(12,2)) 
    
    0 讨论(0)
  • 2020-12-23 12:21

    DECIMAL has two parts: Precision and Scale. So part of your query will look like this:

    CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))
    

    Precision represents the number of significant digits that are stored for values.
    Scale represents the number of digits that can be stored following the decimal point.

    0 讨论(0)
提交回复
热议问题