lets say i want to store the number after the point which is (76) into a variable now. 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
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:
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.
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. But I would do the math to arrive at a value v
, 0 <= v < 1
Following the MySQL stored program pseudo-code given in the question, something like this:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.