Introduction
PHP provides built-in functions for generating random numbers, formatting numeric values, and rounding decimal numbers. These functions are useful for creating OTPs, generating random product numbers, displaying prices, preparing invoices, and calculating rounded amounts. In this chapter, you will practice rand(), mt_rand(), random_int(), number_format(), round(), ceil(), and floor() through practical PHP examples. Random Numbers, Number Formatting and Rounding Practice Questions with Solution to help you understand the concepts.
Question 1: Generate a Random Number Using rand()
Problem Statement
Write a PHP program to generate a random number between 1 and 100 using the rand() function.
PHP Solution
<?php
$number = rand(1, 100);
echo "Random Number: " . $number;
?>
Sample Output
Random Number: 57
Explanation
The rand() function generates a random integer between the minimum and maximum values provided.
1is the minimum value.100is the maximum value.
The output will change each time the program runs.
Concepts Covered
rand()function- Random integer generation
- Minimum and maximum values
Question 2: Generate a Random Number Using mt_rand()
Problem Statement
Generate a random number between 1000 and 9999 using the mt_rand() function.
PHP Solution
<?php
$number = mt_rand(1000, 9999);
echo "Random Number: " . $number;
?>
Sample Output
Random Number: 4826
Explanation
The mt_rand() function generates a random integer within the specified range using the Mersenne Twister algorithm.
Here, PHP generates a number between 1000 and 9999. The result will be different on subsequent executions.
Concepts Covered
mt_rand()function- Random number generation
- Numeric ranges
Question 3: Generate a Secure Random Number Using random_int()
Problem Statement
Generate a cryptographically secure random integer between 100000 and 999999 using random_int().
PHP Solution
<?php
$otp = random_int(100000, 999999);
echo "Generated OTP: " . $otp;
?>
Sample Output
Generated OTP: 736251
Explanation
The random_int() function generates a cryptographically secure random integer within the specified range.
It is suitable for security-sensitive random values, such as OTP generation. Unlike rand() and mt_rand(), it is designed for security-related use.
The sample OTP is only an example. Every execution may generate a different number.
Concepts Covered
random_int()- Secure random number generation
- Six-digit number generation
- OTP basics
Question 4: Generate a Random Dice Number
Problem Statement
Create a simple dice program that generates a random number between 1 and 6 using rand().
PHP Solution
<?php
$dice = rand(1, 6);
echo "Dice Result: " . $dice;
?>
Sample Output
Dice Result: 4
Explanation
A standard dice has six possible outcomes: 1, 2, 3, 4, 5, and 6.
The rand(1, 6) function generates one random integer within this range.
Concepts Covered
- Random number generation
rand()- Dice simulation
Question 5: Format a Number With Thousand Separators
Problem Statement
A company records total sales of 2500000. Display the amount with comma separators using number_format().
PHP Solution
<?php
$totalSales = 2500000;
$result = number_format($totalSales);
echo "Total Sales: " . $result;
?>
Sample Output
Total Sales: 2,500,000
Explanation
The number_format() function formats a number by adding thousands separators.
By default, it uses a comma as the thousands separator and displays no decimal places.
Concepts Covered
number_format()- Thousands separators
- Sales amount formatting
Question 6: Format a Price With Two Decimal Places
Problem Statement
A product costs ₹1499.5. Display the price with two decimal places and a comma separator.
PHP Solution
<?php
$productPrice = 1499.5;
$result = number_format($productPrice, 2);
echo "Product Price: ₹" . $result;
?>
Sample Output
Product Price: ₹1,499.50
Explanation
The number_format() function accepts the number of decimal places as its second argument.
Here:
1499.5is the original price.2specifies two decimal places.- PHP adds a comma as the thousands separator.
The result is displayed as 1,499.50.
Concepts Covered
number_format()- Decimal formatting
- Price display
Question 7: Round a Decimal Number Using round()
Problem Statement
A product price is ₹2499.756. Round it to two decimal places using round().
PHP Solution
<?php
$price = 2499.756;
$result = round($price, 2);
echo "Rounded Price: ₹" . number_format($result, 2);
?>
Sample Output
Rounded Price: ₹2,499.76
Explanation
The round() function rounds a decimal number to the nearest value.
The second argument specifies the number of decimal places.
Here, round($price, 2) rounds 2499.756 to 2499.76. The number_format() function then displays it with a comma separator.
Concepts Covered
round()- Decimal rounding
- Two decimal places
number_format()
Question 8: Round a Number Up Using ceil()
Problem Statement
A delivery company calculates a delivery charge of ₹125.25. Round it upward to the nearest whole number using ceil().
PHP Solution
<?php
$deliveryCharge = 125.25;
$result = ceil($deliveryCharge);
echo "Final Delivery Charge: ₹" . $result;
?>
Sample Output
Final Delivery Charge: ₹126
Explanation
The ceil() function always rounds a number upward to the nearest integer.
For example:
ceil(125.25)returns126.ceil(125.01)returns126.ceil(125.00)returns125.
Concepts Covered
ceil()- Rounding upward
- Delivery charge calculation
Question 9: Round a Number Down Using floor() in PHP
Problem Statement
An employee completes 8.75 working hours. Display only the completed whole hours using floor().
PHP Solution
<?php
$workingHours = 8.75;
$result = floor($workingHours);
echo "Completed Hours: " . $result;
?>
Sample Output
Completed Hours: 8
Explanation
The floor() function rounds a number downward to the nearest integer.
Here, 8.75 becomes 8 because the decimal portion is removed by rounding downward.
Concepts Covered
floor()in PHP- Rounding downward
- Working hours calculation
Question 10: Generate a Random Discount and Calculate the Final Price
Problem Statement
An online store wants to offer a random discount between 5% and 20% on a product priced at ₹5,499.99.
Generate a random discount, calculate the discount amount, and display the final price with two decimal places.
PHP Solution
<?php
$productPrice = 5499.99;
$discountRate = random_int(5, 20);
$discountAmount = ($productPrice * $discountRate) / 100;
$finalPrice = round($productPrice - $discountAmount, 2);
echo "Original Price: ₹" . number_format($productPrice, 2) . "\n";
echo "Discount Rate: " . $discountRate . "%\n";
echo "Discount Amount: ₹" . number_format($discountAmount, 2) . "\n";
echo "Final Price: ₹" . number_format($finalPrice, 2);
?>
Sample Output
Original Price: ₹5,499.99
Discount Rate: 12%
Discount Amount: ₹660.00
Final Price: ₹4,839.99
Explanation
The program performs four main operations:
random_int(5, 20)generates a secure random discount percentage.- The discount amount is calculated by multiplying the product price by the discount rate and dividing by 100.
- The discount is subtracted from the original price.
round()keeps the final price at two decimal places, whilenumber_format()displays the amounts clearly.
The sample output uses a 12% discount. Your actual output may be different each time the program runs.
Concepts Covered
random_int()- Random discount generation
- Percentage calculation
round()number_format()- Practical shopping calculations
Key Takeaways
rand()generates a random integer within a specified range.mt_rand()generates random integers using the Mersenne Twister algorithm.random_int()generates cryptographically secure random integers.- Use
random_int()instead ofrand()ormt_rand()for security-sensitive values. number_format()adds thousands separators and controls decimal places.round()rounds a number to the nearest value.ceil()rounds a number upward.floor()in PHP rounds a number downward.- Random number functions are useful for dice games, sample data, and random selections.
- Number formatting and rounding are useful for invoices, shopping websites, and financial reports.
Frequently Asked Questions
1. What is a random number in PHP?
A random number is a value generated by PHP within a specified range. Functions such as rand(), mt_rand(), and random_int() can generate random integers.
2. What is the difference between rand() and mt_rand()?
Both functions generate random integers. rand() uses the standard random number generator, while mt_rand() uses the Mersenne Twister algorithm.
3. Which PHP function is best for generating secure random numbers?
random_int() is recommended for security-sensitive random integers because it uses a cryptographically secure source of randomness.
4. How can I generate a six-digit random number in PHP?
Use random_int(100000, 999999) to generate a random six-digit integer.
5. What is the use of number_format() in PHP?
The number_format() function formats numbers with thousands separators and optional decimal places.
6. What is the difference between round(), ceil(), and floor() in PHP?
round()rounds to the nearest value.ceil()rounds upward.floor()rounds downward.
7. How can I display a price with two decimal places?
Use number_format($price, 2) to display a price with two decimal places and thousands separators.
8. Can random_int() generate numbers between any two values?
Yes. You can specify a minimum and maximum integer, such as random_int(10, 500).
9. Does rand() generate the same number every time?
Not necessarily. It generates a random value, so the result can change each time the program runs. Random sequences can be made predictable in testing environments by controlling the random seed, but this should not be used for security-sensitive values.
10. Where are random number and formatting functions used in real PHP projects?
They are commonly used in OTP generation, games, discount systems, invoice preparation, billing applications, shopping websites, and financial reports.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
