Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zeros in decimal value with changing length

Tags:

mysql

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

like image 743
Chris Morgan Avatar asked Nov 01 '11 15:11

Chris Morgan


People also ask

How do you get rid of trailing zeros after a decimal?

You can remove trailing zeros using TRIM() function. The syntax is as follows.

How do you remove trailing zeros from strings?

Algorithm. Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.

What is the rule for trailing zeros?

To determine the number of significant figures in a number use the following 3 rules: Non-zero digits are always significant. Any zeros between two significant digits are significant. A final zero or trailing zeros in the decimal portion ONLY are significant.


1 Answers

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`; 
like image 51
Christopher McGowan Avatar answered Oct 05 '22 22:10

Christopher McGowan