HOME       >>       Programming

Remove Unnecessary Decimals With Php?


Amezis

I have a MySQL DECIMAL field allowing up to 3 decimals to the number. However, many of the numbers only have one decimal. An example is 5.2. I want the script to echo ONLY 5.2 and not 5.200. However, if the number is 5.211, I want it to echo the whole number, so I can't just use the round() function. Is there a way to do this?


shadowx

**EDIT**

sorry completely missed this part

so I can't just use the round() function.

However i tested round() on numbers like "5.11" and as ive posted below by rounding to three decimals it will do nothing to change the number unless it ends in a zero in which case it simply strips the zero and nothing more. which explains why this posts assumes you dont understand round();! sorry! But ill leave it as it is for other people to read and hopefully it will be a good solution to your problem

**/ edit***

there is a built in function called round(); which i just found in the php manual, link: http://forums.xisto.com/no_longer_exists/

Basically it rounds any decimal number to a spcified number of digits after the decimal point, eg:

round(*NUMBER*, *DECIMAL PLACES*);
round(3.001, 3);

this would output "3.001" because it ends in a one and is being rounded to three decimal places therefore nothing is changed as it already is 3 DP's

round(3.010, 3);

This would give "3.01" as you can see the last zero has been stripped.


there is a limit to this function though because it cant handle numbers containg commas such as "1,000.32" so providing your numbers arent formatted with commas for every thousand and million etc...you will be fine to use this function. The link i gave also has a lot of info in the case your numbers are formatted with commas.

Amezis

Oh, I didn't know that it would strip the extra zeros. Well, thanks, it works now


jlhaslip

There is also a method to format output from the print command.Check out the php.net manual for the printf function or the sprintf function.



VIEW ORIGINAL REGISTER GET FREE HOSTING

Xisto.com offers Free Web Hosting to its Members for their participation in this Community. We moderate all content posted here but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 2001-2019 by Xisto Corporation. All Rights Reserved.