Math

The Math module provides a comprehensive set of mathematical functions and utilities for FiveM resource development. It extends the standard Lua math library with additional functionality.

round

Rounds a number to the specified number of decimal places.

B2Lib.Math.round(num, decimals)

Parameters:

  • num (number): The number to round

  • decimals (number, optional): Number of decimal places (default: 0)

Returns: number - The rounded number

Example:

local rounded = B2Lib.Math.round(3.14159, 2) -- Returns 3.14
local wholeNumber = B2Lib.Math.round(3.7) -- Returns 4

clamp

Clamps a value between minimum and maximum bounds.

B2Lib.Math.clamp(value, min, max)

Parameters:

  • value (number): The value to clamp

  • min (number): The minimum allowed value

  • max (number): The maximum allowed value

Returns: number - The clamped value

Example:

local health = B2Lib.Math.clamp(playerHealth, 0, 100)
local speed = B2Lib.Math.clamp(vehicleSpeed, 0, 200)

lerp

Performs linear interpolation between two values.

B2Lib.Math.lerp(a, b, t)

Parameters:

  • a (number): The start value

  • b (number): The end value

  • t (number): The interpolation factor (0.0 = a, 1.0 = b)

Returns: number - The interpolated value

Example:

local smoothValue = B2Lib.Math.lerp(currentPos, targetPos, 0.1)
local fadeAlpha = B2Lib.Math.lerp(0, 255, fadeProgress)

distance2D

Calculates the Euclidean distance between two 2D points.

B2Lib.Math.distance2D(x1, y1, x2, y2)

Parameters:

  • x1 (number): X coordinate of the first point

  • y1 (number): Y coordinate of the first point

  • x2 (number): X coordinate of the second point

  • y2 (number): Y coordinate of the second point

Returns: number - The distance between the two points

Example:

local dist = B2Lib.Math.distance2D(player.x, player.y, target.x, target.y)

distance3D

Calculates the Euclidean distance between two 3D points or vectors.

B2Lib.Math.distance3D(pos1, pos2)

Parameters:

  • pos1 (vector3|table): The first position

  • pos2 (vector3|table): The second position

Returns: number - The distance between the two positions

Example:

local playerCoords = GetEntityCoords(PlayerPedId())
local targetCoords = vector3(100, 200, 30)
local dist = B2Lib.Math.distance3D(playerCoords, targetCoords)

normalize

Maps a value from one range to another range.

B2Lib.Math.normalize(value, min, max, newMin, newMax)

Parameters:

  • value (number): The value to normalize

  • min (number): The current range minimum

  • max (number): The current range maximum

  • newMin (number): The target range minimum

  • newMax (number): The target range maximum

Returns: number - The mapped value in the new range

Example:

-- Convert world coordinates to screen coordinates
local screenX = B2Lib.Math.normalize(worldX, -1000, 1000, 0, 1920)

-- Convert health percentage to color intensity
local redIntensity = B2Lib.Math.normalize(health, 0, 100, 255, 0)

toRadians

Converts degrees to radians.

B2Lib.Math.toRadians(degrees)

Parameters:

  • degrees (number): The angle in degrees

Returns: number - The angle in radians

Example:

local radians = B2Lib.Math.toRadians(90) -- Returns π/2
local heading = B2Lib.Math.toRadians(GetEntityHeading(vehicle))

toDegrees

Converts radians to degrees.

B2Lib.Math.toDegrees(radians)

Parameters:

  • radians (number): The angle in radians

Returns: number - The angle in degrees

Example:

local degrees = B2Lib.Math.toDegrees(math.pi) -- Returns 180

getAngle

Calculates the angle between two 2D points.

B2Lib.Math.getAngle(x1, y1, x2, y2)

Parameters:

  • x1 (number): X coordinate of the first point

  • y1 (number): Y coordinate of the first point

  • x2 (number): X coordinate of the second point

  • y2 (number): Y coordinate of the second point

Returns: number - The angle in radians

Example:

local playerCoords = GetEntityCoords(PlayerPedId())
local targetCoords = GetEntityCoords(targetPed)
local angle = B2Lib.Math.getAngle(playerCoords.x, playerCoords.y, targetCoords.x, targetCoords.y)

randomFloat

Generates a random floating-point number between min and max.

B2Lib.Math.randomFloat(min, max)

Parameters:

  • min (number): The minimum value (inclusive)

  • max (number): The maximum value (exclusive)

Returns: number - A random float in the specified range

Example:

local randomSpeed = B2Lib.Math.randomFloat(50.0, 120.0)
local randomDelay = B2Lib.Math.randomFloat(1000, 5000)

randomInt

Generates a random integer between min and max.

B2Lib.Math.randomInt(min, max)

Parameters:

  • min (number): The minimum value (inclusive)

  • max (number): The maximum value (inclusive)

Returns: number - A random integer in the specified range

Example:

local randomDamage = B2Lib.Math.randomInt(10, 50)
local randomIndex = B2Lib.Math.randomInt(1, #playerList)

isEven

Checks if a number is even.

B2Lib.Math.isEven(num)

Parameters:

  • num (number): The number to check

Returns: boolean - True if the number is even, false otherwise

isOdd

Checks if a number is odd.

B2Lib.Math.isOdd(num)

Parameters:

  • num (number): The number to check

Returns: boolean - True if the number is odd, false otherwise

isPrime

Checks if a number is prime.

B2Lib.Math.isPrime(num)

Parameters:

  • num (number): The number to check

Returns: boolean - True if the number is prime, false otherwise

factorial

Calculates the factorial of a number.

B2Lib.Math.factorial(num)

Parameters:

  • num (number): The number to calculate factorial for

Returns: number - The factorial of the number

gcd

Calculates the greatest common divisor of two numbers.

B2Lib.Math.gcd(a, b)

Parameters:

  • a (number): First number

  • b (number): Second number

Returns: number - The greatest common divisor

lcm

Calculates the least common multiple of two numbers.

B2Lib.Math.lcm(a, b)

Parameters:

  • a (number): First number

  • b (number): Second number

Returns: number - The least common multiple

formatNumber

Formats a number with thousands separators.

B2Lib.Math.formatNumber(num, separator)

Parameters:

  • num (number): The number to format

  • separator (string, optional): The separator character (default: ",")

Returns: string - The formatted number

Example:

local formatted = B2Lib.Math.formatNumber(1234567) -- Returns "1,234,567"
local formatted2 = B2Lib.Math.formatNumber(1234567, ".") -- Returns "1.234.567"

formatCurrency

Formats a number as currency.

B2Lib.Math.formatCurrency(amount, symbol, decimals)

Parameters:

  • amount (number): The amount to format

  • symbol (string, optional): The currency symbol (default: "$")

  • decimals (number, optional): Number of decimal places (default: 2)

Returns: string - The formatted currency

Example:

local price = B2Lib.Math.formatCurrency(1234.56) -- Returns "$1,234.56"
local euros = B2Lib.Math.formatCurrency(1234.56, "€") -- Returns "€1,234.56"

percentage

Calculates the percentage of a value relative to a total.

B2Lib.Math.percentage(value, total)

Parameters:

  • value (number): The value

  • total (number): The total

Returns: number - The percentage (0-100)

Example:

local healthPercent = B2Lib.Math.percentage(currentHealth, maxHealth)

pointInCircle

Checks if a point is inside a circle.

B2Lib.Math.pointInCircle(pointX, pointY, circleX, circleY, radius)

Parameters:

  • pointX (number): X coordinate of the point

  • pointY (number): Y coordinate of the point

  • circleX (number): X coordinate of the circle center

  • circleY (number): Y coordinate of the circle center

  • radius (number): Radius of the circle

Returns: boolean - True if the point is inside the circle

pointInRectangle

Checks if a point is inside a rectangle.

B2Lib.Math.pointInRectangle(pointX, pointY, rectX, rectY, width, height)

Parameters:

  • pointX (number): X coordinate of the point

  • pointY (number): Y coordinate of the point

  • rectX (number): X coordinate of the rectangle (top-left)

  • rectY (number): Y coordinate of the rectangle (top-left)

  • width (number): Width of the rectangle

  • height (number): Height of the rectangle

Returns: boolean - True if the point is inside the rectangle

rgbToHex

Converts RGB color values to hexadecimal.

B2Lib.Math.rgbToHex(r, g, b)

Parameters:

  • r (number): Red component (0-255)

  • g (number): Green component (0-255)

  • b (number): Blue component (0-255)

Returns: string - The hexadecimal color code

Example:

local hex = B2Lib.Math.rgbToHex(255, 0, 0) -- Returns "#FF0000"

hexToRgb

Converts hexadecimal color to RGB values.

B2Lib.Math.hexToRgb(hex)

Parameters:

  • hex (string): The hexadecimal color code

Returns: table - RGB values {r, g, b}

Example:

local rgb = B2Lib.Math.hexToRgb("#FF0000") -- Returns {r=255, g=0, b=0}

rgbToHsv

Converts RGB color values to HSV.

B2Lib.Math.rgbToHsv(r, g, b)

Parameters:

  • r (number): Red component (0-255)

  • g (number): Green component (0-255)

  • b (number): Blue component (0-255)

Returns: table - HSV values {h, s, v}

hsvToRgb

Converts HSV color values to RGB.

B2Lib.Math.hsvToRgb(h, s, v)

Parameters:

  • h (number): Hue (0-360)

  • s (number): Saturation (0-100)

  • v (number): Value (0-100)

Returns: table - RGB values {r, g, b}

Configuration

Configure the math system in config.lua:

Config.Math = {
    defaultDecimals = 2,        -- Default decimal places for rounding
    currencySymbol = "$",       -- Default currency symbol
    thousandsSeparator = ",",   -- Default thousands separator
    decimalSeparator = ".",     -- Default decimal separator
    debugMode = false           -- Enable debug logging
}

Troubleshooting

Precision Issues

  1. Use appropriate decimal places for rounding

  2. Be aware of floating-point precision limitations

  3. Use integer operations when possible for exact results

  4. Consider using string formatting for display purposes

Performance Considerations

  1. Cache frequently calculated values

  2. Use simpler functions when precision isn't critical

  3. Avoid unnecessary conversions between number types

  4. Use built-in math functions when available

Invalid Input Handling

  1. Validate input parameters before calculations

  2. Check for division by zero in custom functions

  3. Ensure angles are in expected ranges

  4. Verify color values are within valid ranges (0-255 for RGB)

Common Mistakes

  1. Mixing degrees and radians in calculations

  2. Not handling edge cases in geometric functions

  3. Incorrect range mapping with normalize function

  4. Using wrong coordinate systems for distance calculations

Last updated