PHP Luminova: Utility Class for Basic Math Operations
Calculate numeric values and convert units, currencies, and coordinates.
Luminova’s Math Helpers cover arithmetic, rounding, formatting, conversions, and coordinate validation. The examples use Math for numeric operations, Converter for conversions, Validator for coordinate checks, and Random for random integer strings.
Usage Examples
Distance Between Coordinates
Distance between two points (latitude, longitude):
use Luminova\Utility\Converter;
$distanceKm = Converter::coordinates(12.971603, 77.594605, 13.035542, 77.597100); // default 'km'
$distanceMi = Converter::coordinates(12.971603, 77.594605, 13.035542, 77.597100, 'mi'); // in miles
$distanceFt = Converter::coordinates(12.971603, 77.594605, 13.035542, 77.597100, 'ft'); // in feetLatitude & Longitude Validation
use Luminova\Utility\Validator;
// Check latitude
Validator::isLat(12.971603); // true
Validator::isLat(91); // false (out of range)
Validator::isLat(12.9716032, true, 6); // false (strict, up to 6 decimals)
// Check longitude
Validator::isLng(77.594605); // true
Validator::isLng(181); // false (out of range)
// Check both coordinates
Validator::isLatLng('12.971603', '77.594605'); // true
Validator::isLatLng('12.9716032', '77.5946052', true); // true (strict)
Validator::isLatLng('12.97160321', '77.59460521', true, 6); // false (too many decimals)Currency & Financial Calculations
use Luminova\Utility\Converter;
use Luminova\Utility\Math;
// Format currency
echo Converter::currency(5000); // "$5,000.00" (default USD)
echo Converter::currency(5000, 'EUR'); // "€5,000.00"
echo Converter::currency(5000, 'JPY', 'ja-JP'); // "¥5,000"
// Calculate average rating
$average = Converter::rating(5, 42.5, true); // 8.50 (rounded)
// Average of numbers
$avg = Math::average(10, 20, 30, 40, 50); // 30
// Money formatting
Converter::money(5000, 2); // "5,000.00"
// Percentages, discounts, interest
Converter::percentage(10, of: 5000); // 500
Converter::discount(5000, 10); // 4500
Converter::interest(5000, 10); // 5500Byte & Unit Conversions
use Luminova\Utility\Converter;
// Convert human-readable sizes to bytes
$bytes = Converter::toBytes('1KB'); // 1024
$bytes = Converter::toBytes('1.5MB'); // 1572864
// Convert bytes to readable format
echo Converter::toUnit(1024); // 1.00
echo Converter::toUnit(1048576, 2, true); // "1.00 MB"
// Convert milliseconds to human-readable time
echo Converter::toTimeUnit(1500); // "1.50" (seconds not displayed)
echo Converter::toTimeUnit(1500, 2, true); // "1.50 s"
echo Converter::toTimeUnit(60000, 2, true, true); // "1.00 minutes"Number & Math Utilities
use Luminova\Utility\Math;
// Basic math
$sum = Math::add(10, 20, 30); // 60
$difference = Math::subtract(50, 20); // 30
$product = Math::multiply(2, 3, 4); // 24
$quotient = Math::divide(10, 2); // 5
$quotientByZero = Math::divide(10, 0); // null
// Clamp values
$clamped = Math::clamp(120, 0, 100); // 100
$clamped = Math::clamp(-5, 0, 100); // 0
// GCD & LCM
$gcd = Math::gcd(24, 36); // 12
$lcm = Math::lcm(4, 6); // 12
// Prime check
Math::isPrime(17); // true
Math::isPrime(18); // false
// Even & Odd checks
Math::isEven(10); // true
Math::isOdd(7); // trueGenerate Big Integer
use Luminova\Utility\Random;
// Generate a random BIGINT (default UNSIGNED range)
$bigint = Random::bigInteger();
echo $bigint; // e.g., "12345678901234567890"
// Generate a BIGINT within a custom range
$bigint = Random::bigInteger('1000000000000', '9999999999999');
echo $bigint; // e.g., "5482938475623"
// Generate a SIGNED BIGINT
$bigint = Random::bigInteger('-9223372036854775808', '9223372036854775807');
echo $bigint; // e.g., "-1234567890123456789"Class Definition
- Full namespace:
Luminova\Utility\Math - This class is final.
Methods
toUnit
Available as Converter::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 function toUnit(
float|int $bytes,
int $decimals = 2,
bool $withName = false,
bool $unixName = false,
bool $trimZeros = false
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$bytes | float\|int | Byte value to convert. |
$decimals | int | Number of decimal places (default: 2). |
$withName | bool | Whether to include the unit name (default: false). |
$unixName | bool | Whether to use Unix-style unit names such as K, M, and G (default: false). |
$trimZeros | bool | Whether to remove trailing decimal zeros (default: false). |
Return:
string - Returns the formatted byte value, optionally with its unit name.
toBytes
Available as Converter::toBytes().
Converts a unit name to bytes.
public static function toBytes(string $size): intParameters:
| Parameter | Type | Description |
|---|---|---|
$size | string | Size to convert, such as 1KB, 2MB, or 1.5GB. |
Return:
int - Returns the size in bytes, or 0 for an invalid size.
toTimeUnit
Available as Converter::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 function toTimeUnit(
float|int $milliseconds,
int $decimals = 2,
bool $withName = false,
bool $withFullName = false,
bool $trimZeros = true
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$milliseconds | float\|int | Time value in milliseconds. |
$decimals | int | Number of decimal places (default: 2). |
$withName | bool | Whether to include the unit name (default: false). |
$withFullName | bool | Whether to use the full unit name instead of its abbreviation (default: false). |
$trimZeros | bool | Whether to remove trailing decimal zeros (default: true). |
Return:
string - Returns the formatted time value.
average
Calculate the average of a giving numbers.
public static function average(int|float ...$numbers): ?floatParameters:
| Parameter | Type | Description |
|---|---|---|
$numbers | int\|float | Input arguments integers or float values to calculate the average. |
Return:
float|null - Return the average of the passed numbers.
rating
Available as Converter::rating().
Calculate the average rating based on the number of reviews and total rating points.
public static function rating(
int $reviews = 0,
float $rating = 0,
bool $round = false
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$reviews | int | Number of reviews (default: 0). |
$rating | float | Total rating points (default: 0). |
$round | bool | Whether to round the result to 2 decimal places (default: false). |
Return:
float - Returns the average rating.
Example
The average of the below rating is: 8.50.
use Luminova\Utility\Converter;
echo Converter::rating(5, 42.5, true);money
Available as Converter::money().
Formats currency with decimal places and comma separation.
public static function money(
mixed $amount,
int $decimals = 2
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$amount | mixed | Amount to format. |
$decimals | int | Number of decimal places (default: 2). |
Return:
string - Returns the formatted amount, or 0.00 for a non-numeric value.
currency
Available as Converter::currency().
Format a number as a currency string using your application local as the default currency locale.
public static function currency(
float $number,
string $code = 'USD',
?string $locale = null
): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$number | float | Amount to format. |
$code | string | ISO 4217 currency code (default: USD). |
$locale | string\|null | Locale to use for currency formatting (default: null). |
Return:
string|false - Returns the formatted currency string, or false if formatting fails.
crypto
Available as Converter::crypto().
Format a number to it's cryptocurrency length.
public static function crypto(
string|float|int $amount,
string $currency = 'BTC',
?int $precision = null,
bool $trimZeros = false
): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$amount | string\|float\|int | Cryptocurrency amount to format. |
$currency | string | The network currency code, e.g. BTC, ETH, USDT (default: 'BTC'). |
$precision | int\|null | Override decimals (e.g. 2 for UI display) (default: null). |
$trimZeros | bool | Strip trailing zeros ("1.5" instead of "1.50000000") (default: false). |
Return:
string|false - Formatted amount, or false if not a finite number.
Available Cryptos
BTC- Bitcoin.ETH- Ethereum.LTC- Litecoin.XRP- Ripple Credits.DOGE- Doge Coin.
distance
Available as Converter::distance().
Convert a distance between units. The coordinate example calculates distance between two locations.
public static function distance(
float|int $value,
string $from,
string $to,
int $precision = 2
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | float\|int | Distance value to convert. |
$from | string | Source distance unit. |
$to | string | Target distance unit. |
$precision | int | Number of decimal places for the result (default: 2). |
Return:
float - Returns the converted distance.
Throws:
InvalidArgumentException - If either distance unit is unsupported.
coordinates
Available as Converter::coordinates().
Calculate the great-circle distance between two latitude and longitude pairs using the Haversine formula. Accepted units are km, m, mi, nmi, yd, ft, and cm.
public static function coordinates(
float|string $originLat,
float|string $originLng,
float|string $destLat,
float|string $destLng,
string $unit = 'km'
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$originLat | float\|string | Start latitude in decimal degrees. |
$originLng | float\|string | Start longitude in decimal degrees. |
$destLat | float\|string | Destination latitude in decimal degrees. |
$destLng | float\|string | Destination longitude in decimal degrees. |
$unit | string | Distance unit (default: 'km'). |
Return:
float - Distance in the requested unit.
Throws:
- Luminova\Exceptions\InvalidArgumentException If the unit is unsupported.
add
Add the supplied numbers.
public static function add(float|int ...$numbers): float|intParameters:
| Parameter | Type | Description |
|---|---|---|
$numbers | float\|int | Numbers to add. |
Return:
float|int - The sum, or 0 with no arguments.
subtract
Subtract one number from another.
public static function subtract(float|int $a, float|int $b): float|intParameters:
| Parameter | Type | Description |
|---|---|---|
$a | float\|int | Starting value. |
$b | float\|int | Value to subtract. |
Return:
float|int - The difference.
multiply
Multiply the supplied numbers.
public static function multiply(float|int ...$numbers): float|intParameters:
| Parameter | Type | Description |
|---|---|---|
$numbers | float\|int | Factors to multiply. |
Return:
float|int - The product, or 1 with no arguments.
divide
Divide one number by another.
public static function divide(float|int $a, float|int $b): ?floatParameters:
| Parameter | Type | Description |
|---|---|---|
$a | float\|int | Dividend. |
$b | float\|int | Divisor. |
Return:
float|null - The quotient as a float, or null if the divisor is the integer 0.
Throws:
DivisionByZeroErrorif the divisor is floating-point zero.
clamp
Constrain a number to an inclusive range.
public static function clamp(float|int $value, float|int $min, float|int $max): float|intParameters:
| Parameter | Type | Description |
|---|---|---|
$value | float\|int | Value to constrain. |
$min | float\|int | Lower bound. |
$max | float\|int | Upper bound. Supply a value greater than or equal to the lower bound. |
Return:
float|int - The value within the range, or the nearest bound when outside it.
gcd
Calculate the greatest common divisor of two integers.
public static function gcd(int $a, int $b): intParameters:
| Parameter | Type | Description |
|---|---|---|
$a | int | First integer. |
$b | int | Second integer. |
Return:
int - The nonnegative greatest common divisor.
lcm
Calculate the least common multiple of two integers.
public static function lcm(int $a, int $b): intParameters:
| Parameter | Type | Description |
|---|---|---|
$a | int | First integer. |
$b | int | Second integer. |
Return:
int - The nonnegative least common multiple, or 0 if either value is zero. Use inputs whose product fits in a PHP integer.
isPrime
Check whether an integer is prime.
public static function isPrime(int $number): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$number | int | Integer to check. |
Return:
bool - true if the integer is prime, otherwise false.
isEven
Check whether an integer is even.
public static function isEven(int $number): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$number | int | Integer to check. |
Return:
bool - true if the integer is even, otherwise false.
isOdd
Check whether an integer is odd.
public static function isOdd(int $number): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$number | int | Integer to check. |
Return:
bool - true if the integer is odd, otherwise false.
fixed
Format a number with optional rounding.
public static function fixed(string|float|int $number, ?int $decimals = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$number | string\|float\|int | The value to format. |
$decimals | int\|null | Number of decimal places (null = no formatting) (default: null). |
Return:
string - Return the formatted and rounded numeric string.
floor
Round a number down (toward negative infinity) with optional precision.
This behaves like PHP's native floor() when precision is 0, but allowsrounding to a fixed number of decimal places or to larger units whenusing negative precision.
public static function floor(float|int $value, int $precision = 0): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | float\|int | The numeric value to round down. |
$precision | int | Number of decimal digits to preserve (default: 0). |
Return:
float - Return the floored value rounded to the next lowest integer.
Examples:
Basic usage:
use Luminova\Utility\Math;
Math::floor(4.7); // 4.0
Math::floor(-4.7); // -5.0With decimal precision:
use Luminova\Utility\Math;
Math::floor(4.567, 2); // 4.56
Math::floor(9.999, 1); // 9.9With negative precision:
use Luminova\Utility\Math;
Math::floor(1234, -2); // 1200
Math::floor(987, -1); // 980Edge cases:
use Luminova\Utility\Math;
Math::floor(5, 2); // 5.0
Math::floor(0, 3); // 0.0discount
Available as Converter::discount().
Calculate a percentage discount of a given value.
This method calculates the discounted amount based on the given rate.
public static function discount(
string|float|int $value,
string|float|int $rate,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | string\|float\|int | Original value. |
$rate | string\|float\|int | Discount rate as a percentage. |
$precision | int\|null | Number of decimal places to round the result (default: null). |
Return:
float - Returns the value after applying the discount.
Throws
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
interest
Available as Converter::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 function interest(
string|float|int $value,
string|float|int $rate,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$value | string\|float\|int | Original value. |
$rate | string\|float\|int | Interest rate as a percentage. |
$precision | int\|null | Number of decimal places to round the result (default: null). |
Return:
float - Returns the value after applying the interest.
Throws:
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
percentage
Available as Converter::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 function percentage(
string|float|int $rate,
string|float|int $of,
?int $precision = null
): floatParameters:
| Parameter | Type | Description |
|---|---|---|
$rate | string\|float\|int | Percentage rate. |
$of | string\|float\|int | Base value used to calculate the percentage. |
$precision | int\|null | Number of decimal places to round the result (default: null). |
Return:
float - Returns the calculated percentage value.
Throws:
InvalidArgumentException - If non-numeric inputs, negative rates, or invalid precision.
bigInteger
Available as Random::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 function bigInteger(?string $min = null, ?string $max = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$min | string\|null | The minimum value (default: self::UINT64_MIN). |
$max | string\|null | The maximum value (default: self::UINT64_MAX). |
Return:
string - Returns the generated random 64-bit integer as a string.
isLat
Available as Validator::isLat().
Checks if a value is a valid latitude.
Latitude must be between -90 and 90 degrees.
public static function isLat(mixed $lat, bool $strict = false, ?int $precision = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lat | mixed | The latitude value to check. |
$strict | bool | Whether to enforce decimal format and precision (default: false). |
$precision | int\|null | Maximum decimal places allowed when strict (default: null). |
Return:
bool - Returns true if the latitude is valid, otherwise false.
isLng
Available as Validator::isLng().
Checks if a value is a valid longitude.
Longitude must be between -180 and 180 degrees.
public static function isLng(mixed $lng, bool $strict = false, ?int $precision = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lng | mixed | The longitude value to check. |
$strict | bool | Whether to enforce decimal format and precision (default: false). |
$precision | int\|null | Maximum decimal places allowed when strict (default: null). |
Return:
bool - Returns true if the longitude is valid, otherwise false.
isLatLng
Available as Validator::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 function isLatLng(
mixed $lat,
mixed $lng,
bool $strict = false,
?int $precision = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$lat | mixed | Latitude value. |
$lng | mixed | Longitude value. |
$strict | bool | When true, also checks numeric format and precision (default: false). |
$precision | int\|null | Maximum allowed decimal places when $strict is true (default: null). |
Return:
bool - Returns true if both latitude and longitude are valid, otherwise false.