将小数点后的数字存储到 MySQL 中的变量中

storing the numbers after the decimal point into a variable in MySQL

假设我现在想将 (76) 点之后的数字存储到一个变量中。我该怎么做? 我将在下面给出一个场景。

declare x (3,2);
set x = 323.76;
declare y int;
select cast(substring_index(x, '.', -1) as unsigned) into y;

如有任何帮助,我们将不胜感激。

作为过程或函数和触发器,您可以使用您的代码(稍作更改)

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `mantisse`()
BEGIN
declare x DECIMAL(8,2);

declare y int;
set x = 323.76;
select cast(substring_index(x, '.', -1) as unsigned) into y;
INSERT INTO mytable VALUE (y);
END$$
DELIMITER ;

或者如果您想在查询中使用它,您可以使用用户定义的变量

set @x = 323.96;
select cast(substring_index(@x, '.', -1) as unsigned) into @y;
INSERT INTO mytable VALUE (@y);

你已经有了一个字符串,所以使用 SUBSTRING 得到 9

set @x = 323.96;
select cast(SUBSTRING(substring_index(@x, '.', -1),1,1) as unsigned) into @y;
SELECT @y;
INSERT INTO mytable VALUE (@y);

这当然也适用于 Proecdure

您可以使用 MOD 函数轻松地从数字中获取小数:

SET @num = 323.76;
SET @decimals = MOD(@num, 1) * 100;
SELECT @decimals; -- 76.00

除以1,用MOD函数可以得到余数,即0.76,然后乘以100即可

如果我理解规范,它似乎很奇怪。我会使用 substring_index 函数来 trim 关闭之前的所有内容,包括点。但我会计算得出一个值 v,0 <= v < 1

在问题中给出的 MySQL 存储程序伪代码之后,是这样的:

DECLARE x DECIMAL(5,2);
DECLARE y BIGINT;

SET x := 323.76;
SET y := SUBSTRING_INDEX( ABS(x)-FLOOR(ABS(x)) ,'.',-1) + 0;

可能有更简单的方法来做到这一点,但这是一种满足我对规范的理解的方法。

作为导出 y 值的表达式的演示,请考虑:

SELECT _x
     , SUBSTRING_INDEX( ABS(_x)-FLOOR(ABS(_x)) ,'.',-1) + 0 AS _y
  FROM ( SELECT 0 AS _x
         UNION ALL SELECT 0.1
         UNION ALL SELECT 2.0 
         UNION ALL SELECT 3.3
         UNION ALL SELECT -4.00
         UNION ALL SELECT -5.55
         UNION ALL SELECT 623.76
         UNION ALL SELECT -723.76
       ) t

returns

_x       _y  
-------  -----
   0.00      0
   0.10     10
   2.00      0
   3.30     30
  -4.00      0
  -5.55     55
 623.76     76
-723.76     76