DEV Community

 Tresor
Tresor

Posted on

I built a fluent Numberable API for Laravel (v1.0.0)

Laravel has Stringable for strings, but numeric logic in apps often still looks messy.

I just released laravel-numberable v1.0.0: a small package for fluent numeric operations and formatting in Laravel.

Why

Numbers in apps usually need more than + and -:

  • parsing user input
  • currency / percentage formatting
  • rounding
  • comparisons
  • business rule helpers

I wanted something chainable and expressive.

Install

composer require tresor-kasenda/laravel-numberable
Enter fullscreen mode Exit fullscreen mode

Example

$price = number(1999.99)
    ->withLocale('en_US')
    ->withCurrency('USD');

$price->asCurrency();
Enter fullscreen mode Exit fullscreen mode

Fluent math

$total = number(120)
    ->add(30)
    ->multiply(1.2)
    ->round(2);
Enter fullscreen mode Exit fullscreen mode

Utilities

number(15)->clamp(0, 10);   // 10
number(10.0)->trim();       // 10
number(17)->isPrime();      // true
number(12)->isEven();       // true
number(10)->between(5, 15); // true
Enter fullscreen mode Exit fullscreen mode

Formatting

number(0.157)->asPercentage();
number(1532000)->asAbbreviated();
number(1048576)->asFileSize();
number(21)->asOrdinal();
Enter fullscreen mode Exit fullscreen mode

Also supports

  • localized parsing (from('1 234,50', 'fr_FR'))
  • when() / unless() pipelines
  • macros and custom formats

Compatibility

  • Laravel 10 / 11 / 12
  • PHP 8.3 / 8.4

Links

Feedback is welcome, especially around API naming and missing numeric helpers.

Tags: laravel php opensource webdev

Top comments (0)