Represents a percentage value with validation and formatting.

Percentage is immutable and can be created from decimal (0.5) or percentage (50) values. Supports common percentage operations and formatting.

const result = Percentage.fromDecimal(0.25);
if (result.isSuccess) {
const pct = result.value;
console.log(pct.asPercentage()); // 25
console.log(pct.format()); // "25%"
}

Hierarchy (View Summary)

Methods

  • Compares this Value Object with another for equality. Value Objects are equal if they are of the same type and all equality components match.

    Parameters

    • other: ValueObject

      The other Value Object to compare with

    Returns boolean

    true if the Value Objects are equal, false otherwise

  • Gets the value as a decimal (0-1).

    Returns number

    The decimal representation

    const pct = Percentage.fromPercentage(25).unwrap();
    console.log(pct.asDecimal()); // 0.25
  • Gets the value as a percentage (0-100).

    Returns number

    The percentage representation

    const pct = Percentage.fromDecimal(0.25).unwrap();
    console.log(pct.asPercentage()); // 25
  • Applies this percentage to a number.

    Parameters

    • amount: number

      The amount to apply the percentage to

    Returns number

    The calculated result

    const discount = Percentage.fromPercentage(20).unwrap();
    const price = 100;
    console.log(discount.of(price)); // 20
  • Checks if this percentage is zero.

    Returns boolean

    true if the percentage is 0%

    const zero = Percentage.zero();
    console.log(zero.isZero()); // true
  • Checks if this percentage is 100%.

    Returns boolean

    true if the percentage is 100%

    const full = Percentage.full();
    console.log(full.isFull()); // true
  • Formats the percentage as a string.

    Parameters

    • decimals: number = 2

      Number of decimal places (default: 0)

    Returns string

    A formatted string representation

    const pct = Percentage.fromDecimal(0.2575).unwrap();
    console.log(pct.format()); // "25.75%"
    console.log(pct.format(0)); // "26%"
    console.log(pct.format(1)); // "25.8%"

Properties

value: number