[PHP] Round numbers with PHP

Dieser Beitrag ist auch verfügbar in: German

Hi,

today again a bit PHP. A small tip about handling with numbers in PHP. Or more explicit, round off numbers.

PHP comes already with several functions to handle numbers. Four of them are number_format, ceil, floor and round. My personal favorite is  number_format. Why?

Because this function does not just round, it is also formatting the number. The syntax is:

Syntax: string <strong>number_format</strong> (float number [, int <code>decimals [, string decimal separator, string thousands separator]])

This function can be called with 2 or 4 parameter, but not with 3. So

number_format (<code>number);
number_format (<code>number, <code>decimals)
oder
number_format (<code><code>number, <code>decimals, decimal separator, thousands separator);

An example:

number_format (15329.6956, 2, ",", ".");

The output will be: 15.329,70

The next function, resp. functions are ceil and floor. This functions simply round up (ceil) or down (floor). The syntax is float ceil (float $number) reps. float floor (float $number). In both cases will be the number rounded up- or down on the next integer.

Last but not least the round function. It’s the middle way between the last 3 functions. It rounds a floating-point number up or down and you can provide a decimal place. The syntax is:
float <strong>round</strong> ( float <code>$number[, int $<code><code><code>decimals = 0 [, int $mode]] )

An example:

round(15.1698, 2) results: 15.17

Please note that you’re working always with the English number format while you’re programming. Decimal places are separated with a dot “.” and the thousands separator (if they have a separator) with a comma “,”.

Best regards
Gordon

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*