Kategori

# Round Number in PHP

Discussion Board : One of the important functions in the mathematical calculations, that do rounding numbers with PHP
Requirements : Webserver package, already installed.

One friend who is building an ecommerce never ask something like this: “How can I create a program that, items weighing less than 1 kg to 1 kg is considered 1 kg, then more than 1 kg to 2 kg is considered 2 kg, and so on? “
The problem above can be written as follows:
1> = weight> 0 —> considered to be 1 kg
2> weight => 1 —> 2 kg is considered
etc. ..

Actually, this problem is not a complex problem. Absolutely not complicated in fact. Examples of the above case is just one example of cases that can be resolved easily by Rounding. In PHP, the known three mathematical functions that can be used for rounding, namely ceil, Floor, and Round. 1. Rounding upwards (ceil).
For example for the above case

[sourcecode language=”php”]
<?php
\$berat1 = 0.5;
\$berat2 = 1.5;
\$berat3 = 2;
echo ‘berat 1 =’.ceil(\$berat1); echo ‘<br />’;
echo ‘berat 2 =’.ceil(\$berat2); echo ‘<br />’;
echo ‘berat 3 =’.ceil(\$berat3);
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 1
berat 2 = 2
berat 3 = 2
So the conclusion is that the PHP function ceil will perform rounding upwards on the given number. This function will produce the nearest integer value of upwards of a number.

2. Rounding down (floor).
Floor used for rounding down. See the example below,

[sourcecode language=”php”]
<?php
\$berat1 = 0.5;
\$berat2 = 1.5;
\$berat3 = 2;
echo ‘berat 1 =’.floor(\$berat1); echo ‘<br />’;
echo ‘berat 2 =’.floor(\$berat2); echo ‘<br />’;
echo ‘berat 3 =’.floor(\$berat3);
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 0
berat 2 = 1
berat 3 = 2
Contrary to ceil, the floor will do the rounding to the nearest integer value down of a number.

3. Rounding to the nearest
ROUND round a number to the nearest value in accordance with the number behind the comma deciman desired. For example,

[sourcecode language=”php”]
<?php
\$berat1 = 0.58989;
\$berat2 = 1.6;
\$berat3 = 2.4;
echo ‘berat 1 =’.round(\$berat1, 2); echo ‘<br />’; // with 2 decimal
echo ‘berat 2 =’.round(\$berat2, 0); echo ‘<br />’; // 0 decimal
echo ‘berat 3 =’.round(\$berat3); // without parameter, so it will rounded in to the nearest integer
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 0.59
berat 2 = 2
berat 3 = 2

Hope it hels! 😀 Happy coding 😀 ## Oleh littleflow3r

obviously, a girl. with sweet smile, off course. turning her 21 years trapped on Informatics departement and just started to having some crush with it lately. she uses wordpress. she loves php. she loves to satisfied her shopping hobbies just via looking around in online shop. oh yeah, she got an A for her english subject^^

This site uses Akismet to reduce spam. Learn how your comment data is processed.