Jump to content
xisto Community
Sign in to follow this  
Amezis

Remove Unnecessary Decimals With Php?

Recommended Posts

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?

Share this post


Link to post
Share on other sites

**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 :D

**/ 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.
Edited by shadowx (see edit history)

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.