PHPackages                             jbzoo/simpletypes - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. jbzoo/simpletypes

ActiveLibrary

jbzoo/simpletypes
=================

The universal PHP library to convert any values and measures

7.0.2(7mo ago)641.8k31MITPHPPHP ^8.2CI passing

Since Jul 3Pushed 7mo ago6 watchersCompare

[ Source](https://github.com/JBZoo/SimpleTypes)[ Packagist](https://packagist.org/packages/jbzoo/simpletypes)[ RSS](/packages/jbzoo-simpletypes/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (28)Used By (1)

JBZoo / SimpleTypes
===================

[](#jbzoo--simpletypes)

[![CI](https://github.com/JBZoo/SimpleTypes/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/JBZoo/SimpleTypes/actions/workflows/main.yml?query=branch%3Amaster) [![Coverage Status](https://camo.githubusercontent.com/a244c482f7517775b75ccf38d6deeac408f313773732283b3bb4b7eb2594f948/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4a425a6f6f2f53696d706c6554797065732f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/JBZoo/SimpleTypes?branch=master) [![Psalm Coverage](https://camo.githubusercontent.com/a9f19fc8240fa9e73246c05297aca4e39bf3665c95ed8b29d5db2d7c8ae54b24/68747470733a2f2f73686570686572642e6465762f6769746875622f4a425a6f6f2f53696d706c6554797065732f636f7665726167652e737667)](https://shepherd.dev/github/JBZoo/SimpleTypes) [![Psalm Level](https://camo.githubusercontent.com/704c832d756f4db3cfb2fc35084db1d62010dfc22079871dbc084f7d4f947ff8/68747470733a2f2f73686570686572642e6465762f6769746875622f4a425a6f6f2f53696d706c6554797065732f6c6576656c2e737667)](https://shepherd.dev/github/JBZoo/SimpleTypes) [![CodeFactor](https://camo.githubusercontent.com/294c978ec03184339c9b9f5960ed9d002fbac4e17373d65bc95cd436fa071f39/68747470733a2f2f7777772e636f6465666163746f722e696f2f7265706f7369746f72792f6769746875622f6a627a6f6f2f73696d706c6574797065732f6261646765)](https://www.codefactor.io/repository/github/jbzoo/simpletypes/issues)[![Stable Version](https://camo.githubusercontent.com/378a1d52b6c0bc01ad5b691d38a6165f171095afa4f0f99389f3f08b5fd1b29b/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f73696d706c6574797065732f76657273696f6e)](https://packagist.org/packages/jbzoo/simpletypes/) [![Total Downloads](https://camo.githubusercontent.com/955d066af6e61292733d3060f6a2d4f541aa2b7b75d628cb62ffb17c84b39e06/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f73696d706c6574797065732f646f776e6c6f616473)](https://packagist.org/packages/jbzoo/simpletypes/stats) [![Dependents](https://camo.githubusercontent.com/c53a4c8393ecdbcda7a72645c74c2b978825001ca73a0129342a4a0fdcd9e37a/68747470733a2f2f706f7365722e707567782e6f72672f6a627a6f6f2f73696d706c6574797065732f646570656e64656e7473)](https://packagist.org/packages/jbzoo/simpletypes/dependents?order_by=downloads) [![GitHub License](https://camo.githubusercontent.com/a5b686fbdaf78763675a9b3d68d20dc91b97680a7a2c0020aeedd7bc71706c48/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6a627a6f6f2f73696d706c657479706573)](https://github.com/JBZoo/SimpleTypes/blob/master/LICENSE)

A universal PHP library for converting and manipulating values with units of measurement including money, weight, length, temperature, volume, area, and more. Features smart parsing, arithmetic operations, unit conversion, and flexible output formatting.

Installation
------------

[](#installation)

```
composer require jbzoo/simpletypes
```

Features
--------

[](#features)

- **Smart Parser**: Handles various input formats, decimal symbols, whitespace, and case variations
- **Type System**: Built-in support for Money, Weight, Length, Temperature, Volume, Area, Time, Info, and Degree
- **Arithmetic Operations**: Add, subtract, multiply, divide with automatic unit conversion
- **Method Chaining**: Fluent interface for complex calculations
- **Flexible Output**: Text, HTML, and input field rendering with customizable formatting
- **Configuration**: Extensible configuration system for custom types and conversion rules
- **Debug Support**: Built-in logging and debugging capabilities

Quick Start
-----------

[](#quick-start)

```
use JBZoo\SimpleTypes\Config;
use JBZoo\SimpleTypes\Money;
use JBZoo\SimpleTypes\ConfigMoney;

// Set config object for all Money objects as default
Config::registerDefault('money', new ConfigMoney());

// Create objects with automatic parsing
$money  = new Money('10 eur');
$weight = new Weight('1000'); // Gram is default unit
$length = new Length('500 km');
$money  = new Money('100500 usd', new ConfigMoney()); // Custom configuration
```

Built-in Types
--------------

[](#built-in-types)

SimpleTypes comes with comprehensive configurations for common measurement types:

- **[Area](src/config/area.php)** - Square meters, feet, acres, hectares, etc.
- **[Degree](src/config/degree.php)** - Angular measurements (degrees, radians)
- **[Info](src/config/info.php)** - Digital storage (bytes, KB, MB, GB, TB)
- **[Length](src/config/length.php)** - Meters, feet, miles, kilometers, etc.
- **[Money](src/config/money.php)** - Currency conversion and formatting
- **[Temperature](src/config/temp.php)** - Celsius, Fahrenheit, Kelvin, Rankine
- **[Time](src/config/time.php)** - Seconds, minutes, hours, days, etc.
- **[Volume](src/config/volume.php)** - Liters, gallons, cubic meters, etc.
- **[Weight](src/config/weight.php)** - Grams, kilograms, pounds, ounces, etc.

Custom types can be easily created by extending the base configuration classes.

Smart Parser
------------

[](#smart-parser)

The parser automatically handles various input formats and edge cases:

```
$money = new Money(' - 1 2 3 , 4 5 6 rub ');    // Parses to -123.456 rubles
$money = new Money('1.0e+18 EUR ');             // Scientific notation support
$money = new Money('  EuR 3,50   ');            // Case insensitive, handles whitespace
$money = new Money('usd');                      // Creates zero-value USD object
```

Method Chaining
---------------

[](#method-chaining)

Perform complex calculations with fluent interface:

```
$value = (new Money('4.95 usd'))
    ->add('10 usd')                         // $14.95
    ->subtract('2 eur')                     // $10.95
    ->negative()                            // -$10.95
    ->getClone()                            // copy of object is created
    ->division(5)                           // -$2.19
    ->multiply(10)                          // -$21.90
    ->convert('eur')                        // -10.95€ (For easy understanding we use 1 EUR = 2 USD)
    ->customFunc(function (Money $value) {  // sometimes we would like something more than plus/minus ;)
        $value
            ->add(new Money('600 rub'))     // 1.05€ (1 EUR = 50 RUB)
            ->add('-500%');                 // -4.2€
    })
    ->abs();                                // 4.2€
```

Arithmetic Operations
---------------------

[](#arithmetic-operations)

Multiple ways to perform calculations:

```
// Using objects
$usd = new Money('10 usd');
$usd->add(new Money('10 eur'));

// Method chaining
$usd = (new Money('10 usd'))->add(new Money('10 eur'));

// String input with automatic parsing
$usd->add('10 eur');

// Using default unit from configuration
$usd->add('10');

// Array format
$usd->add(['10', 'eur']);
```

**Supported Operations:**

- Addition and subtraction with automatic unit conversion
- Multiplication and division
- Custom functions via closures
- Sign operations (negative, positive, absolute value)
- Percentage calculations
- Value and unit modifications
- Object cloning
- Unit/currency conversion
- Rounding and formatting
- Comparison operations
- Serialization support

Value Comparison
----------------

[](#value-comparison)

Compare values with automatic unit conversion:

```
$kg = new Weight('1 kg'); // one kilogram
$lb = new Weight('2 lb'); // two pounds

var_dump($kg->compare($lb));            // false ("==" by default)
var_dump($kg->compare($lb, '=='));      // false
var_dump($kg->compare($lb, ''));       // true
var_dump($kg->compare($lb, '>='));      // true
```

Using string input with smart parsing:

```
$kg = new Weight('1 kg');
$lb = new Weight('2 lb');

var_dump($kg->compare('1000 g'));       // true
var_dump($kg->compare('2 lb', '=='));   // false
var_dump($kg->compare('2 lb', ''));    // true
var_dump($kg->compare('2 lb', '>='));   // true
```

Percentage Calculations
-----------------------

[](#percentage-calculations)

Calculate percentage differences between values:

```
$origPrice = new Money('100 usd');
$realPrice = new Money('40 eur');

$diff = $realPrice->percent($origPrice);
echo $diff->text(); // 80%

$discount = $realPrice->percent($origPrice, true); // revert flag added
echo $discount->text(); // 20%
```

Magic Methods
-------------

[](#magic-methods)

**Serialization Support:**

```
$valBefore = $this->val('500 usd');
$valString = serialize($valBefore);
$valAfter  = unserialize($valString)->convert('eur');
$valBefore->compare($valAfter);// true
```

**String Conversion:**

```
$val = $this->val('500 usd');
echo $val; // "$500.00"
```

**Object Invocation:**

```
$val = $this->val('10 eur');
// Convert to different currency
$val('usd'); // Converts to USD using exchange rates
// Set new value and currency
$val('100 rub');
$val('100', 'uah');
```

Output Formatting
-----------------

[](#output-formatting)

### Text Output

[](#text-output)

```
$value = new Money('-50.666666 usd');
echo $value->text();            // "-$50.67"
echo $value->text('rub');       // "-1 266,67 руб." (convert for display only)
echo $value->noStyle('rub');    // "-1 266,67" (number without currency symbol)
```

### HTML Output

[](#html-output)

```
echo (new Money('-50.666666 usd'))->html('rub'); // HTML with data attributes for JavaScript
```

Generated HTML (formatted for readability):

```

        -1 266,67
        руб.

```

### HTML Input Fields

[](#html-input-fields)

```
echo $value->htmlInput('rub', 'input-name-attr');
```

Generated HTML (formatted for readability):

```

```

**Note:** The HTML output includes extensive data attributes to enable client-side JavaScript operations without server round-trips.

Custom Configuration
--------------------

[](#custom-configuration)

Create custom types by extending the base configuration class. Here's an example for digital storage:

```
/**
 * Example: Digital storage configuration
 */
class ConfigInfo extends Config
{
    // Default unit for parsing
    public $default = 'byte';

    // Enable debug logging
    public $isDebug = true;

    // Define conversion rules and formatting
    public function getRules()
    {
        return [
            'byte' => [
                'rate' => 1 // Base unit
            ],

            'kb' => [
                'symbol'          => 'KB',                     // Display symbol
                'round_type'      => Formatter::ROUND_CLASSIC, // Rounding method
                'round_value'     => Formatter::ROUND_DEFAULT, // Decimal precision
                'num_decimals'    => '2',                      // Decimal places
                'decimal_sep'     => '.',                      // Decimal separator
                'thousands_sep'   => ' ',                      // Thousands separator
                'format_positive' => '%v %s',                  // Positive format (%v=value, %s=symbol)
                'format_negative' => '-%v %s',                 // Negative format
                'rate'            => 1024,                     // Conversion rate from base unit
            ],

            'mb' => [
                'symbol' => 'MB',
                'rate'   => 1024 * 1024,
            ],

            'gb' => [
                'symbol' => 'GB',
                'rate'   => 1024 * 1024 * 1024,
            ],

            'bit' => [
                'symbol' => 'Bit',
                'rate'   => function ($value, $to) { // Custom conversion function
                    return ($to === 'bit') ? $value * 8 : $value / 8;
                },
            ],
        ];
    }
}
```

### Using Custom Configuration

[](#using-custom-configuration)

```
// Create configuration instance
$config = new ConfigInfo();

// Register as default for all Info objects
Config::registerDefault('info', $config);
$info1 = new Info('700 MB');
$info2 = new Info('1.4 GB');

// Or pass configuration directly
$info1 = new Info('700 MB', $config);
$info2 = new Info('1.4 GB', $config);

// Perform calculations
echo $info2->subtract($info1)->dump() . PHP_EOL;
echo $info2->convert('mb')->dump() . PHP_EOL;
print_r($info2->logs());
```

**Output:**

```
0.71640625 gb; id=4
733.6 mb; id=4
Array
(
    [0] => Id=4 has just created; dump="1.4 gb"
    [1] => Subtract "700 mb"; New value = "0.71640625 gb"
    [2] => Converted "gb"=>"mb"; New value = "733.6 mb"; 1 gb = 1024 mb
)

```

Debug and Introspection
-----------------------

[](#debug-and-introspection)

### Operation History

[](#operation-history)

Track all operations performed on an object:

```
print_r($value->logs());

/**
 * Array
 * (
 *     [0]  => Id=16 has just created; dump="4.95 usd"
 *     [1]  => Add "10 usd"; New value = "14.95 usd"
 *     [2]  => Subtract "2 eur"; New value = "10.95 usd"
 *     [3]  => Set negative; New value = "-10.95 usd"
 *     [4]  => Cloned from id=16 and created new with id=19; dump=-10.95 usd
 *     [5]  => Division with "5"; New value = "-2.19 usd"
 *     [6]  => Multiply with "10"; New value = "-21.9 usd"
 *     [7]  => Converted "usd"=>"eur"; New value = "-10.95 eur"; 1 usd = 0.5 eur
 *     [8]  => --> Function start
 *     [9]  => Add "600 rub"; New value = "1.05 eur"
 *     [10] => Add "-500 %"; New value = "-4.2 eur"
 *     [11] =>  Set positive/abs; New value = "4.2 eur"
 * )
 */
```

### Internal State

[](#internal-state)

Access raw internal data without formatting:

```
echo $value->dump(); // "4.2 eur; id=19"
```

### Object Identification

[](#object-identification)

```
echo $value->getId(); // "19"
```

### Value Access

[](#value-access)

```
echo $value->val(); // "4.2"
```

### Unit Access

[](#unit-access)

```
echo $value->rule(); // "eur"
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- jbzoo/utils ^7.3

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance62

Regular maintenance activity

Popularity28

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity86

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 99.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~143 days

Recently: every ~355 days

Total

27

Last Release

233d ago

Major Versions

1.4.2 → 2.0.02020-07-14

2.2.1 → 3.0.02022-06-06

3.0.0 → 7.0.02023-07-09

PHP version history (8 changes)1.0PHP &gt;=5.4.1

1.2.3PHP &gt;=5.3.27

1.2.6PHP &gt;=5.3.1

2.0.0PHP &gt;=7.2

2.0.1PHP ^7.2

3.0.0PHP &gt;=7.4

7.0.0PHP ^8.1

7.0.2PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/75e6de2785f6d099699f430ff58404af4fc0e83060d2953028c9664a54704a5f?d=identicon)[smetdenis](/maintainers/smetdenis)

---

Top Contributors

[![SmetDenis](https://avatars.githubusercontent.com/u/1118678?v=4)](https://github.com/SmetDenis "SmetDenis (250 commits)")[![bitdeli-chef](https://avatars.githubusercontent.com/u/3092978?v=4)](https://github.com/bitdeli-chef "bitdeli-chef (1 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

arithmeticcurrenciescurrency-coverterhtmlmeasuremeasuresmoneysmart-parseruniversal-php-libraryweightmoneyconvertertimenumberspeedinfoweighttemperaturearealengthpressurevolumedegreeacceleration

### Embed Badge

![Health badge](/badges/jbzoo-simpletypes/health.svg)

```
[![Health](https://phpackages.com/badges/jbzoo-simpletypes/health.svg)](https://phpackages.com/packages/jbzoo-simpletypes)
```

###  Alternatives

[mjaschen/phpgeo

Simple Yet Powerful Geo Library

1.6k8.6M22](/packages/mjaschen-phpgeo)[kwn/number-to-words

Multi language standalone PHP number to words converter. Fully tested, open for extensions and new languages.

4235.0M21](/packages/kwn-number-to-words)[wapmorgan/morphos

A morphological solution for Russian and English language written completely in PHP. Provides classes to inflect personal names, geographical names, decline and pluralize nouns, generate cardinal and ordinal numerals, spell out money amounts and time.

8351.3M7](/packages/wapmorgan-morphos)[sonata-project/intl-bundle

Symfony SonataIntlBundle

2159.0M48](/packages/sonata-project-intl-bundle)[cartalyst/converter

A framework agnostic measurement conversion and formatting package featuring multiple types of measurements and currency conversion.

88434.4k7](/packages/cartalyst-converter)[ujjwal/currency-converter

Currency Converter Class with features of caching and identifying currency from country Code

49225.4k](/packages/ujjwal-currency-converter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
