Luminova Framework

PHP Luminova: Utility Class for Basic Math Operations

Last updated: 2026-11-28 20:57:12

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 feet

Latitude & 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);                    // 5500

Byte & 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);                              // true

Generate 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
): string

Parameters:

ParameterTypeDescription
$bytesfloat\|intByte value to convert.
$decimalsintNumber of decimal places (default: 2).
$withNameboolWhether to include the unit name (default: false).
$unixNameboolWhether to use Unix-style unit names such as K, M, and G (default: false).
$trimZerosboolWhether 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): int

Parameters:

ParameterTypeDescription
$sizestringSize 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
): string

Parameters:

ParameterTypeDescription
$millisecondsfloat\|intTime value in milliseconds.
$decimalsintNumber of decimal places (default: 2).
$withNameboolWhether to include the unit name (default: false).
$withFullNameboolWhether to use the full unit name instead of its abbreviation (default: false).
$trimZerosboolWhether 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): ?float

Parameters:

ParameterTypeDescription
$numbersint\|floatInput 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
): float

Parameters:

ParameterTypeDescription
$reviewsintNumber of reviews (default: 0).
$ratingfloatTotal rating points (default: 0).
$roundboolWhether 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
): string

Parameters:

ParameterTypeDescription
$amountmixedAmount to format.
$decimalsintNumber 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|false

Parameters:

ParameterTypeDescription
$numberfloatAmount to format.
$codestringISO 4217 currency code (default: USD).
$localestring\|nullLocale 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|false

Parameters:

ParameterTypeDescription
$amountstring\|float\|intCryptocurrency amount to format.
$currencystringThe network currency code, e.g. BTC, ETH, USDT (default: 'BTC').
$precisionint\|nullOverride decimals (e.g. 2 for UI display) (default: null).
$trimZerosboolStrip 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
): float

Parameters:

ParameterTypeDescription
$valuefloat\|intDistance value to convert.
$fromstringSource distance unit.
$tostringTarget distance unit.
$precisionintNumber 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'
): float

Parameters:

ParameterTypeDescription
$originLatfloat\|stringStart latitude in decimal degrees.
$originLngfloat\|stringStart longitude in decimal degrees.
$destLatfloat\|stringDestination latitude in decimal degrees.
$destLngfloat\|stringDestination longitude in decimal degrees.
$unitstringDistance unit (default: 'km').

Return:

float - Distance in the requested unit.

Throws:


add

Add the supplied numbers.

public static function add(float|int ...$numbers): float|int

Parameters:

ParameterTypeDescription
$numbersfloat\|intNumbers 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|int

Parameters:

ParameterTypeDescription
$afloat\|intStarting value.
$bfloat\|intValue to subtract.

Return:

float|int - The difference.


multiply

Multiply the supplied numbers.

public static function multiply(float|int ...$numbers): float|int

Parameters:

ParameterTypeDescription
$numbersfloat\|intFactors 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): ?float

Parameters:

ParameterTypeDescription
$afloat\|intDividend.
$bfloat\|intDivisor.

Return:

float|null - The quotient as a float, or null if the divisor is the integer 0.

Throws:

  • DivisionByZeroError if 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|int

Parameters:

ParameterTypeDescription
$valuefloat\|intValue to constrain.
$minfloat\|intLower bound.
$maxfloat\|intUpper 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): int

Parameters:

ParameterTypeDescription
$aintFirst integer.
$bintSecond 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): int

Parameters:

ParameterTypeDescription
$aintFirst integer.
$bintSecond 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): bool

Parameters:

ParameterTypeDescription
$numberintInteger 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): bool

Parameters:

ParameterTypeDescription
$numberintInteger 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): bool

Parameters:

ParameterTypeDescription
$numberintInteger 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): string

Parameters:

ParameterTypeDescription
$numberstring\|float\|intThe value to format.
$decimalsint\|nullNumber 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): float

Parameters:

ParameterTypeDescription
$valuefloat\|intThe numeric value to round down.
$precisionintNumber 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.0

With decimal precision:

use Luminova\Utility\Math;

Math::floor(4.567, 2);   // 4.56
Math::floor(9.999, 1);   // 9.9

With negative precision:

use Luminova\Utility\Math;

Math::floor(1234, -2);   // 1200
Math::floor(987, -1);    // 980

Edge cases:

use Luminova\Utility\Math;

Math::floor(5, 2);       // 5.0
Math::floor(0, 3);       // 0.0

discount

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
): float

Parameters:

ParameterTypeDescription
$valuestring\|float\|intOriginal value.
$ratestring\|float\|intDiscount rate as a percentage.
$precisionint\|nullNumber 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
): float

Parameters:

ParameterTypeDescription
$valuestring\|float\|intOriginal value.
$ratestring\|float\|intInterest rate as a percentage.
$precisionint\|nullNumber 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
): float

Parameters:

ParameterTypeDescription
$ratestring\|float\|intPercentage rate.
$ofstring\|float\|intBase value used to calculate the percentage.
$precisionint\|nullNumber 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 = 18446744073709551615

SIGNED 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): string

Parameters:

ParameterTypeDescription
$minstring\|nullThe minimum value (default: self::UINT64_MIN).
$maxstring\|nullThe 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): bool

Parameters:

ParameterTypeDescription
$latmixedThe latitude value to check.
$strictboolWhether to enforce decimal format and precision (default: false).
$precisionint\|nullMaximum 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): bool

Parameters:

ParameterTypeDescription
$lngmixedThe longitude value to check.
$strictboolWhether to enforce decimal format and precision (default: false).
$precisionint\|nullMaximum 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
): bool

Parameters:

ParameterTypeDescription
$latmixedLatitude value.
$lngmixedLongitude value.
$strictboolWhen true, also checks numeric format and precision (default: false).
$precisionint\|nullMaximum allowed decimal places when $strict is true (default: null).

Return:

bool - Returns true if both latitude and longitude are valid, otherwise false.