简体   繁体   English

MySQL 删除尾随零

[英]MySQL Remove Trailing Zero

Is there a built-in function in MySQL the removes trailing zeros on the right? MySQL 中是否有内置函数可以删除右侧的尾随零?

I have samples and i want my output to be like this:我有样本,我希望我的输出是这样的:

 1.0    ==>   1
 1.50   ==>   1.5
10.030  ==>  10.03
 0.50   ==>   0.5
 0.0    ==>   0

Easiest way by far, just add zero!迄今为止最简单的方法,只需添加零!

Examples:例子:

SET 
    @yournumber1="1.0", 
    @yournumber2="1.50",
    @yournumber3="10.030",
    @yournumber4="0.50",
    @yournumber5="0.0"
;

SELECT 
    (@yournumber1+0),
    (@yournumber2+0),
    (@yournumber3+0),
    (@yournumber4+0),
    (@yournumber5+0)
;

+------------------+------------------+------------------+------------------+------------------+
| (@yournumber1+0) | (@yournumber2+0) | (@yournumber3+0) | (@yournumber4+0) | (@yournumber5+0) |
+------------------+------------------+------------------+------------------+------------------+
|                1 |              1.5 |            10.03 |              0.5 |                0 |
+------------------+------------------+------------------+------------------+------------------+
1 row in set (0.00 sec)

If the column your value comes from is DECIMAL or NUMERIC type, then cast it to string first to make sure the conversion takes place...ex:如果您的值来自 DECIMAL 或 NUMERIC 类型的列,则首先将其转换为字符串以确保发生转换...例如:

SELECT (CAST(`column_name` AS CHAR)+0) FROM `table_name`;

For a shorter way, just use any built-in string function to do the cast:对于更短的方法,只需使用任何内置字符串函数来执行转换:

SELECT TRIM(`column_name`)+0 FROM `table_name`;

it solves my problem using this:它使用这个解决了我的问题:

(TRIM(TRAILING '.' FROM(CAST(TRIM(TRAILING '0' FROM setpoint)AS char)))) AS setpoint

example:例子:

mysql> SELECT testid, designationid, test, measure,
              (TRIM(TRAILING '.' FROM(CAST(TRIM(TRAILING '0' FROM setpoint)AS char)))) AS setpoint,
              (TRIM(TRAILING '.' FROM(CAST(TRIM(TRAILING '0' FROM tmin)AS char)))) AS tmin,
              (TRIM(TRAILING '.' FROM(CAST(TRIM(TRAILING '0' FROM tmax)AS char)))) AS tmax,
       FROM    tests

这是我的方法:

SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM `table`.`column`)) FROM table

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.我在无法修改代码或 SQL 查询的情况下遇到了类似的问题,但我可以修改数据库结构。 So I changed the column format from DECIMAL to FLOAT and it solved my problem.所以我将列格式从 DECIMAL 更改为 FLOAT 并解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM