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条回答
【Aperson】
2楼-- · 2020-01-30 08:02

The best solution I found is to cast your round value to FLOAT:

SELECT CAST(ROUND(1.2345984372, 2) AS FLOAT)
查看更多
来,给爷笑一个
3楼-- · 2020-01-30 08:03

Taking forward the answer provided by @fooquency, if the column is already declared as a DECIMAL with a non-zero value for D in DECIMAL(M, D), we do not need to perform the WHERE condition

WHERE yourfield LIKE '%.%'

as the values in the column will always contain D digits after the decimal dot (.)

查看更多
Rolldiameter
4楼-- · 2020-01-30 08:03

Using ROUND or CEILING, in the query you just have to type:

SELECT ROUND(2/50) 

or

SELECT CEILING(2/50)
查看更多
看我几分像从前
5楼-- · 2020-01-30 08:03
SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' from yourfield)) AS yourfield
FROM yourtable
WHERE yourfield LIKE '%.%'

or

SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' from yourfield)) AS yourfield
FROM yourtable
WHERE instr(yourfield,'.') != 0

work ok but require a "where" clause.

I think the best solution is probably:

SELECT TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM ROUND(yourfield,3))) 
FROM yourtable

as it doesn't require a "where" clause, doesn't require any special code, and also lets you set the maximum precision of the number upfront.

查看更多
Juvenile、少年°
6楼-- · 2020-01-30 08:04

Easiest way by far, just add zero!

Examples:

SET 
    @yournumber1="1.500", 
    @yournumber2="23.030",
    @yournumber3="2.000",
    @yournumber4="4.450"
;

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

+------------------+------------------+------------------+------------------+
| (@yournumber1+0) | (@yournumber2+0) | (@yournumber3+0) | (@yournumber4+0) |
+------------------+------------------+------------------+------------------+
|              1.5 |            23.03 |                2 |             4.45 |
+------------------+------------------+------------------+------------------+
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:

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`;
查看更多
劳资没心,怎么记你
7楼-- · 2020-01-30 08:04

Here's what worked for me:

SINGLE COLUMN:

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

MULTIPLE COLUMNS:

SELECT 
TRIM(column1)+0 AS column1,
TRIM(column2)+0 AS column2,   
TRIM(column3)+0 AS column3,
FROM table_name;
查看更多
登录 后发表回答