Featured Posts

Syntax to Rounding Floating-Point Numbers in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 09-12-2009

1

To round a number to the closest integer, use round( ) :
$number = round(2.4); // $number = 2

To round up, use ceil( ) :
$number = ceil(2.4);// $number = 3

To round down, use floor( ) :
$number = floor(2.4); // $number = 2
If a number falls exactly between two integers, PHP rounds away from 0:
$number = round(2.5); //3

$number = round(-2.5);// -3
To keep a set number of digits after the decimal point, round( ) accepts an optional precision argument. For example, perhaps you are calculating the total price for the items in a user’s shopping cart:
<?php
$cart = 54.23;
$tax = $cart * .05;
$total = $cart + $tax; // $total = 56.9415

$final = round($total, 2); // $final = 56.94
?>

To round a number down, use the floor( ) function:
$number = floor( 2.1);//2
$number = floor( 2.9);//2
$number = floor(-2.1);// -3
$number = floor(-2.9);// -3

While to round up, use the ceil( ) function:
$number = ceil( 2.1);//3
$number = ceil( 2.9);//3
$number = ceil(-2.1);// -2
$number = ceil(-2.9);// -2

These two functions are named because when you’re rounding down, you’re rounding “toward the floor,” and when you’re rounding up, you’re rounding “toward the ceiling.”

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Comments (1)

Hello admin,

For ceil(). If we give more than 5 digits after decimal. Will it give correct answer

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Post a comment

You must be logged in to post a comment.