July 22, 2010

Working with decimal numbers in PHP

Question by The Worst Shady

I want to somehow round the numbers for a rating system in PHP like this:

4.6667 = 4.6

5.0001 = 5.0

Is there any way to do that? (BTW, I read the data from a database.)

Answer by Sarfraz

You are not conforming to any single rule. For example:

4.6667 = 4.6
5.0001 = 5.1

See these functions anyway:

round
ceil
floor

And number_format.

Answer by Starx

Use this:

echo round(1.45667, 2);

The number “2” is how many decimal places you want.

This is output 1.46.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!