phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Rounding a Floating Point Number

Tag: number, round, float   Category: PHP Basic
post: 16 Mar 2008 read: 203


PHP Number Tips - Part 15: If you want to round off a floating-point number, you can use the round( ) function such as:

<?php
//define floating point number
$num = (2/3);

//round to integer
//result: 1
$roundNum = round($num);
echo $roundNum . "\n";

//round to 1 decimal place
//result: 0.7
$roundNum = round($num, 1);
echo $roundNum . "\n";

//round to 3 decimal places
//result: 0.667
$roundNum = round($num, 3);
echo $roundNum;
?>

The round( ) function rounds a number to a specified number of decimal places.Calling round( ) without the optional second argument will make it round into an integer value (0 decimal places). When rounding into an integer, the round( ) function will return the closest integer value. In order to force rounding to a lower or higher integer value, you can use the ceil( ) or floor( ) functions as following:


<?php
//define floating point numbers
$num = (1/3);

$r = round($num);
$c = ceil($num);
$f = floor($num);

//result: "0 1 0"
echo "$r $c $f"
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting