Remove trailing zeros in decimal value with changi

2020-01-30 07:47发布

I have a procedure I am doing that displays odds but the client wants only significant digits to be shown. So, 1.50 would show as '1.5' and 1.00 would show as '1'.

How can I get MySQL to not display trailing zeros;

i.e. in the database:

Odds
1.500
23.030
2.000
4.450

would display as

1.5
23.03
2
4.45

Thanks for any help

标签: mysql
14条回答
你好瞎i
2楼-- · 2020-01-30 08:07

this worked for me.. round the field to 2 decimal places and then trim any trailing zeros

So that 2.10 is 2.1

SELECT trim(round(FIELDNAME,2))+0 
FROM tbl_name
....
查看更多
等我变得足够好
3楼-- · 2020-01-30 08:09

If you are using PHP as the scripting language you may use the following:

$var = (float)$var_having_extra_0; // $var = (float) 17.5000

Or use the PHP floatval function:

$var = floatval($var_having_extra_0); // $var = floatval(17.5000)
查看更多
冷血范
4楼-- · 2020-01-30 08:11

Please use below function , it will take care of number having zero without decimal places i.e 150 etc....

 SET @saved_cs_client     = @@character_set_client;
 SET character_set_client = utf8;
 DELIMITER $$
 USE `mydbname`$$

 DROP FUNCTION IF EXISTS `FN_STRIP_TRAILING_ZER0`$$

 CREATE DEFINER=`mydbuser`@`%` FUNCTION `FN_STRIP_TRAILING_ZER0`(tNumber DECIMAL(10,7)) RETURNS VARCHAR(20) CHARSET utf8

 BEGIN
     DECLARE strBuff VARCHAR(20);
     DECLARE cnt  NUMERIC(2);
     DECLARE tString VARCHAR(20);
     SELECT CAST(tNumber AS CHAR) INTO tString;
     SELECT LOCATE('.',tString) INTO cnt;
     IF cnt > 0 THEN
       SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM tString)) INTO strBuff;   
     ELSE
       SET strBuff = tString;
     END IF;
     RETURN strBuff;
 END$$
 DELIMITER ;
 SET character_set_client = @saved_cs_client;

Addendum:

Typically to call this would involve: SELECT FN_STRIP_TRAILING_ZER0(1.5);

查看更多
Root(大扎)
5楼-- · 2020-01-30 08:13

Try this simply updated Query to remove decimal zeros

SELECT TRIM(TRAILING '.00' FROM price_column)
FROM table_name
查看更多
贼婆χ
6楼-- · 2020-01-30 08:22

I had a similar problem in a situation where I could not modify the code nor the SQL query, but I was allowed to modify the database structure. So I changed the column format from DECIMAL to FLOAT and it solved my problem.

查看更多
够拽才男人
7楼-- · 2020-01-30 08:23

Taking fragments of the others answers in this page I came to this conclusion:

SELECT ( IF(
    myfield LIKE '%.%', 
    TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM myfield)),
    myfield
) ) FROM mytable

Cheers

查看更多
登录 后发表回答