PHP Luminova: Basic Maths Utility Class
Maths class offers static utility methods for common calculations, including currency and unit conversions, averages, ratings, discounts, distance, and interest computations.
The Maths class provides a collection of static utility methods for common mathematical operations. It is designed to simplify development by offering ready-to-use functions without needing to instantiate objects.
The class includes methods for:
- Calculating discounts and interest
- Computing percentages
- Formatting currency values
- Performing arithmetic operations and averages
- Working with bytes, time units, and geographic coordinates
- Checking prime numbers, even/odd numbers, and clamping values
- Calculating GCD and LCM
Usage Examples
Distance Between Coordinates
Distance between two points (latitude, longitude):
use Luminova\Utility\Maths;
$distanceKm = Maths::distance(12.971603, 77.594605, 13.035542, 77.597100); // default 'km'
$distanceMi = Maths::distance(12.971603, 77.594605, 13.035542, 77.597100, 'mi'); // in miles
$distanceFt = Maths::distance(12.971603, 77.594605, 13.035542, 77.597100, 'ft'); // in feetLatitude & Longitude Validation
// Check latitude
Maths::isLat(12.971603); // true
Maths::isLat(91); // false (out of range)
Maths::isLat(12.9716032, true, 6); // true (strict, up to 6 decimals)
// Check longitude
Maths::isLng(77.594605); // true
Maths::isLng(181); // false (out of range)
// Check both coordinates
Maths::isLatLng('12.971603', '77.594605'); // true
Maths::isLatLng('12.9716032', '77.5946052', true); // true (strict)
Maths::isLatLng('12.97160321', '77.59460521', true, 6); // false (too many decimals)Currency & Financial Calculations
use Luminova\Utility\Maths;
// Format currency
echo Maths::currency(5000); // "$5,000.00" (default USD)
echo Maths::currency(5000, 'EUR'); // "€5,000.00"
echo Maths::currency(5000, 'JPY', 'ja-JP'); // "¥5,000"
// Calculate average rating
$average = Maths::rating(5, 42.5, true); // 8.50 (rounded)
// Average of numbers
$avg = Maths::average(10, 20, 30, 40, 50); // 30
// Money formatting
Maths::money(5000, 2); // "5000.00"
// Percentages, discounts, interest
Maths::percentage(10, of: 5000); // 500
Maths::discount(5000, 10); // 4500
Maths::interest(5000, 10); // 5500Byte & Unit Conversions
// Convert human-readable sizes to bytes
$bytes = Maths::toBytes('1KB'); // 1024
$bytes = Maths::toBytes('1.5MB'); // 1572864
// Convert bytes to readable format
echo Maths::toUnit(1024); // 1.00
echo Maths::toUnit(1048576, 2, true); // "1.00 MB"
// Convert milliseconds to human-readable time
echo Maths::toTimeUnit(1500); // "1.50" (seconds not displayed)
echo Maths::toTimeUnit(1500, 2, true); // "1.50 s"
echo Maths::toTimeUnit(60000, 2, true, true); // "1.00 minutes"Number & Math Utilities
// Basic math
$sum = Maths::add(10, 20, 30); // 60
$difference = Maths::subtract(50, 20); // 30
$product = Maths::multiply(2, 3, 4); // 24
$quotient = Maths::divide(10, 2); // 5
$quotientByZero = Maths::divide(10, 0); // null
// Factorial
$fact = Maths::factorial(5); // 120
// Clamp values
$clamped = Maths::clamp(120, 0, 100); // 100
$clamped = Maths::clamp(-5, 0, 100); // 0
// GCD & LCM
$gcd = Maths::gcd(24, 36); // 12
$lcm = Maths::lcm(4, 6); // 12
// Prime check
Maths::isPrime(17); // true
Maths::isPrime(18); // false
// Even & Odd checks
Maths::isEven(10); // true
Maths::isOdd(7); // trueGenerate Big Integer
use Luminova\Utility\Maths;
// Generate a random BIGINT (default UNSIGNED range)
$bigint = Maths::bigInteger();
echo $bigint; // e.g., "12345678901234567890"
// Generate a BIGINT within a custom range
$bigint = Maths::bigInteger('1000000000000', '9999999999999');
echo $bigint; // e.g., "5482938475623"
// Generate a SIGNED BIGINT
$bigint = Maths::bigInteger('-9223372036854775808', '9223372036854775807');
echo $bigint; // e.g., "-1234567890123456789"Class Definition
- Class namespace:
Luminova\Utility\Maths - This class is marked as final and can't be subclassed
Methods
toUnit
Convert a byte value to a human-readable format.
Automatically converts bytes to the most appropriate unit(B, KB, MB, GB, TB, PB, EB, ZB, YB) and can optionally append the
public static toUnit(
float|int $bytes,
int $decimals = 2,
bool $withName = false,
bool $trimZeros = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$bytes | int | The byte value to convert. |
$decimals | int | Number of decimal places to include (Default: 2). |
$withName | bool | Whether to append the unit name (default: false). |
$trimZeros | bool | Trim trailing zeros (default: false). |
Return Value:
string - Return the formatted value, optionally including the unit.
toBytes
Converts a unit name to bytes.
public static toBytes(string $units): intParameters:
| Parameter | Type | Description |
|---|---|---|
$units | string | The string representation of the byte size (e.g., '1KB', '2MB'). |
Return Value:
int - Return the size in bytes.
toTimeUnit
Convert time milliseconds to a human-readable time unit.
Automatically chooses the most appropriate time unit:
- milliseconds (
ms), - seconds (
s), - minutes (min),
- hours (h),
- days (d),
- weeks (w).
- months (m).
- years (y).
public static toTimeUnit(
float|int $milliseconds,
int $decimals = 2,
bool $withName = false,
bool $withFullName = false,
bool $trimZeros = true
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$milliseconds | float|int | The time in milliseconds. |
$decimals | int | Number of decimal places (default 2). |
$withName | bool | Number of decimal places (default: false). |
$withFullName | bool | Use full name (e.g., "seconds" instead of "s"). |
$trimZeros | bool | Trim unnecessary decimal zeros (default true). |
Return Value:
string - Return formatted time string.
average
Calculate the average of a giving numbers.
public static average(int|float ...$numbers): float|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$numbers | int|float | The arguments integers or float values to calculate the average - @example average(10, 20, 30, 40, 50) - return 30 as the average. |
Return Value:
float|null - Return the average of the passed numbers.
rating
Calculate the average rating based on the number of reviews and total rating points.
public static rating(int $reviews, float $rating, bool $round = false): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$reviews | int | The total number of reviews. |
$rating | float | The total sum of rating points. |
$round | bool | Whether to round the average to 2 decimal places (default: false). |
Return Value:
float - Return the average rating.
Example
The average of the below rating is: 8.50.
echo Math::rating(5, 42.5, true)money
Formats currency with decimal places and comma separation.
public static money(mixed $amount, int $decimals = 2): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$amount | mixed | The amount you want to format. |
$decimals | int | The decimals places. |
Return Value:
string - Return formatted currency string.
currency
Format a number as a currency string using your application local as the default currency locale.
public static currency(float $number, string $code = 'USD', string|null $locale = null): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$number | float | The number to format. |
$code | string | The currency code (optional). |
$locale | string|null | TOptional pass locale name to use in currency formatting. |
Return Value:
string|false - Return the formatted currency string, or false if unable to format.
crypto
Format a number to it's cryptocurrency length.
public static crypto(int|float|string $amount, string $network = 'BTC'): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$amount | int|float|string | The amount to convert. |
$network | string | The cryptocurrency code (e.g., 'BTC', 'ETH', 'LTC'). |
Return Value:
string|false - The equivalent amount in cryptocurrency.
Available Cryptos
BTC- Bitcoin.ETH- Ethereum.LTC- Litecoin.XRP- Ripple Credits.DOGE- Doge Coin.
distance
Calculate distance between two geographic coordinates.
Uses the Haversine formula to determine the distance between two points on the Earth's surface.
public static distance(
float|string $originLat,
float|string $originLng,
float|string $destLat,
float|string $destLng,
string $unit = 'km'
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$originLat | float|string | The latitude of origin. |
$originLng | float|string | The longitude of origin. |
$destLat | float|string | The latitude of destination. |
$destLng | float|string | The longitude of destination. |
$unit | string | The distance unit (e.g, 'km', 'm', 'mi', 'nmi', 'yd', 'ft', 'cm'). |
Return Value:
float - Returns the distance in the requested unit distance between points.
Throws:
InvalidArgumentException - On invalid unit or coordinates.
fixed
Format a number with optional rounding.
public static fixed(float|int|string $number, ?int $decimals = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$number | float|int|string | The number you want to format. |
$decimals | int|null | The number of decimal places (null for no rounding). |
Return Value:
string - Return the formatted and rounded number.
discount
Calculate a percentage discount of a given value.
This method calculates the discounted amount based on the given rate.
public static discount(
float|int|string $value,
float|int|string $rate,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | float|int|string | The original total value. |
$rate | float|int|string | The discount rate as a percentage. |
$precision | int|null | Optional decimal places to round the result. |
Return Value:
float - Returns the final value after applying the discount.
Throws
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
interest
Calculate a percentage interest of a given value.
This method calculates the total value after adding interest based on the given rate.
public static interest(
float|int|string $value,
float|int|string $rate,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | float|int|string | The original amount. |
$rate | float|int|string | The interest rate as a percentage. |
$precision | int|null | Optional decimal places to round the result. |
Return Value:
float - Returns the final value after applying the interest.
Throws:
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
percentage
Calculate a percentage of a given amount.
This method calculates the absolute value of a percentage from a base value.
Alias rate()
public static percentage(
string|float|int $rate,
string|float|int $of,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$total | float|int|string | The percentage rate to calculate. |
$of | float|int|string | The base value from. |
$precision | int|null | Optional decimal precision (null = no rounding). |
Return Value:
float - Return the percentage amount of given base value.
Throws:
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
bigInteger
Generate a random BIGINT within a specified range.
UNSIGNED BIGINT: 0 to 18,446,744,073,709,551,615 (20 digits):
$min= 0$max= 18446744073709551615SIGNED BIGINT: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (19 digits):
$min= -9223372036854775808$max= 9223372036854775807
public static bigInteger(int $min, int $max): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$min | int | The minimum value (default: 0). |
$max | int | The maximum value (default: 18446744073709551615). |
Return Value:
string - Return a string representation of the generated BIGINT.
isLat
Checks if a value is a valid latitude.
Latitude must be between -90 and 90 degrees.
public static isLat(float|string $lat, bool $strict = false, int $precision = 6): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lat | float|string | The latitude value to check. |
$strict | bool | When true, also checks the numeric format and decimal precision. |
$precision | int | The maximum number of decimal places allowed when $strict is true (default: 6). |
Return Value:
bool - Returns true if the latitude is valid, otherwise false.
isLng
Checks if a value is a valid longitude.
Longitude must be between -180 and 180 degrees.
public static isLng(float|string $lng, bool $strict = false, int $precision = 6): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lng | float|string | The longitude value to check. |
$strict | bool | When true, also checks the numeric format and decimal precision. |
$precision | int | The maximum number of decimal places allowed when $strict is true (default: 6). |
Return Value:
bool - Returns true if the longitude is valid, otherwise false.
isLatLng
Checks if both latitude and longitude values are valid.
- Latitude must be between -90 and 90 degrees.
- Longitude must be between -180 and 180 degrees.
When $strict is true, both values are also checked for numeric format and decimal precision (based on $precision).
public static isLatLng(
float|string $lat,
float|string $lng,
bool $strict = false,
int $precision = 6
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lat | float|string | Latitude value. |
$lng | float|string | Longitude value. |
$strict | bool | When true, also checks numeric format and precision. |
$precision | int | Maximum allowed decimal places when $strict is true (default: 6). |
Return Value:
bool - Returns true if both latitude and longitude are valid, otherwise false.