[英]storing the numbers after the decimal point into a variable in MySQL
lets say i want to store the number after the point which is (76) into a variable now.假设我现在想将 (76) 点之后的数字存储到变量中。 How am i supposed to do that?
我该怎么做? I will give a scenario below.
我将在下面给出一个场景。
declare x (3,2);
set x = 323.76;
declare y int;
select cast(substring_index(x, '.', -1) as unsigned) into y;
Any help would be appreciated.任何帮助,将不胜感激。
As Procedure or a finction and trigger, you can use your code(with a little change)作为过程或函数和触发器,您可以使用您的代码(稍作改动)
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 ;
Or if you want to use it in a query you can use user defined variables或者,如果您想在查询中使用它,您可以使用用户定义的变量
set @x = 323.96;
select cast(substring_index(@x, '.', -1) as unsigned) into @y;
INSERT INTO mytable VALUE (@y);
you have alreadya string so use SUBSTRING to get the 9你已经有一个字符串,所以使用 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);
That works in the Proecdure too of course当然,这也适用于程序
You can easily get decimals from a number using MOD function:您可以使用 MOD function 轻松地从数字中获取小数:
SET @num = 323.76;
SET @decimals = MOD(@num, 1) * 100;
SELECT @decimals; -- 76.00
Dividing by 1, you can get the remainder with MOD function, which is 0.76
, and then you only need to multiply it by 100.除以 1 可以用 MOD function 得到余数,即
0.76
,然后只需乘以 100 即可。
If I'm understanding the specification, it seems rather bizarre.如果我理解规范,那似乎很奇怪。 I'd use the substring_index function to trim off everything before and including the dot.
我会使用 substring_index function 修剪掉包括点之前的所有内容。 But I would do the math to arrive at a value
v
, 0 <= v < 1但我会做数学得出一个值
v
, 0 <= v < 1
Following the MySQL stored program pseudo-code given in the question, something like this:遵循问题中给出的 MySQL 存储程序伪代码,如下所示:
DECLARE x DECIMAL(5,2);
DECLARE y BIGINT;
SET x := 323.76;
SET y := SUBSTRING_INDEX( ABS(x)-FLOOR(ABS(x)) ,'.',-1) + 0;
There might be a simpler way to do it, but this is an approach that satisfies my understanding of the specification.可能有一种更简单的方法可以做到这一点,但这是一种满足我对规范的理解的方法。
As a demonstration of the expression that derives the value of y
, consider:作为导出
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.