Storing Age numbers expressed in decimals in MySQL

liz :

I have an age column that is currently varchar because i cannot figure out how to define it correctly.

the ages look like the following samples:

.03   /   .3  /  1.33  /  20

i tried Decimal (4,2) but then i get something like 82.00! which i dont want. I want under 1 to look like 0.2 or .2, or .25 I want age 82 to be just 82 and age 5 to be just 5.

do I have to do this in php after the case or is there a way to store the numbers without the extra 0's.

storing as varchar displays them correctly but does not allow for the proper search.

Sherif :

How you store a number and how you format it when printing it are not mutually exclusive things. Storing numbers as strings is about the worst thing you can do. Decimal(4,2) tells MySQL to store the number with up to 2 digits of precision for the integral part of your number and up to 2 digits of precision for the fractional part. This says nothing about how those digits can be printed, however. For example printf("%d", 1.01) gives you 1. Whereas printf("%.2f", 1.0123) gives you 1.01.

PHP has several functions that can assist with formatting such as sprintf, and number_format, not to mention Intl's NumberFormatter for i18n.

If all you want is to truncate the right-most 0s from the number when printing it you can try something like rtrim($number, '0.').

echo rtrim(1.00, '0.'); // 1
echo rtrim(1.10, '0.'); // 1.1
echo rtrim(1.11, '0.'); // 1.11
echo rtrim(10.01, '0.'); // 10.01

The only edge case you have to watch out for here is if the number is 0 you will end up with an empty string.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13847&siteId=1