Luminova Framework

PHP Luminova: Basic Maths Utility Class

Last updated: 2026-01-12 12:28:32

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 feet

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

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

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

Parameters:

ParameterTypeDescription
$bytesintThe byte value to convert.
$decimalsintNumber of decimal places to include (Default: 2).
$withNameboolWhether to append the unit name (default: false).
$trimZerosboolTrim 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): int

Parameters:

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

Parameters:

ParameterTypeDescription
$millisecondsfloat|intThe time in milliseconds.
$decimalsintNumber of decimal places (default 2).
$withNameboolNumber of decimal places (default: false).
$withFullNameboolUse full name (e.g., "seconds" instead of "s").
$trimZerosboolTrim 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|null

Parameters:

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

Parameters:

ParameterTypeDescription
$reviewsintThe total number of reviews.
$ratingfloatThe total sum of rating points.
$roundboolWhether 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): string

Parameters:

ParameterTypeDescription
$amountmixedThe amount you want to format.
$decimalsintThe 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|false

Parameters:

ParameterTypeDescription
$numberfloatThe number to format.
$codestringThe currency code (optional).
$localestring|nullTOptional 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|false

Parameters:

ParameterTypeDescription
$amountint|float|stringThe amount to convert.
$networkstringThe 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'
): float

Parameters:

ParameterTypeDescription
$originLatfloat|stringThe latitude of origin.
$originLngfloat|stringThe longitude of origin.
$destLatfloat|stringThe latitude of destination.
$destLngfloat|stringThe longitude of destination.
$unitstringThe 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): string

Parameters:

ParameterTypeDescription
$numberfloat|int|stringThe number you want to format.
$decimalsint|nullThe 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
): float

Parameters:

ParameterTypeDescription
$valuefloat|int|stringThe original total value.
$ratefloat|int|stringThe discount rate as a percentage.
$precisionint|nullOptional 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
): float

Parameters:

ParameterTypeDescription
$valuefloat|int|stringThe original amount.
$ratefloat|int|stringThe interest rate as a percentage.
$precisionint|nullOptional 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
): float

Parameters:

ParameterTypeDescription
$totalfloat|int|stringThe percentage rate to calculate.
$offloat|int|stringThe base value from.
$precisionint|nullOptional 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 = 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 bigInteger(int $min, int $max): string

Parameters:

ParameterTypeDescription
$minintThe minimum value (default: 0).
$maxintThe 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): bool

Parameters:

ParameterTypeDescription
$latfloat|stringThe latitude value to check.
$strictboolWhen true, also checks the numeric format and decimal precision.
$precisionintThe 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): bool

Parameters:

ParameterTypeDescription
$lngfloat|stringThe longitude value to check.
$strictboolWhen true, also checks the numeric format and decimal precision.
$precisionintThe 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
): bool

Parameters:

ParameterTypeDescription
$latfloat|stringLatitude value.
$lngfloat|stringLongitude value.
$strictboolWhen true, also checks numeric format and precision.
$precisionintMaximum allowed decimal places when $strict is true (default: 6).

Return Value:

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