Unit converter and calculator for php

Related tags

Numbers Units
Overview

Unit converter and calculator

This library uses the awesome lisachenko/z-engine to allow mathematical operations on objects, allowing to do stuff like this:

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Foot;

$meter = new Meter(5);
$feet = new Foot(15);

$result = $meter + $feet;
var_dump($result->getValue()); // dumps object of Rikudou\Units\Number\BigNumber which holds the value 9.572 

You need to have ffi enabled and bcmath extension installed.

The units are always in the unit that's first in the operation, meaning if you wanted the result in feet you would just reverse them (or convert them, more on that below):

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Foot;

$meter = new Meter(5);
$feet = new Foot(15);

$result = $feet + $meter;
var_dump($result->getValue()); // dumps object of Rikudou\Units\Number\BigNumber which holds the value 31.40419947506561

The value is always an instance of Rikudou\Units\Number\BigNumber which can be cast to int, float, bool and string. Casting to int and float may be unsafe if working with large numbers.

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Number\BigNumber;

$meter = new Meter(5);
$value = $meter->getValue();

var_dump((int) $value); // int(5)
var_dump((float) $value); // float(5)
var_dump((string) $value); // string(1) "5"
var_dump((bool) $value); // bool(true)

$veryBigValue = $meter * PHP_INT_MAX;
$value = $veryBigValue->getValue();
var_dump((string) $value); // on 64 bit correctly prints string(20) "46116860184273879035"
var_dump((int) $value); // prints int(9223372036854775807) which is the value of PHP_INT_MAX on 64 bits
var_dump((float) $value); // prints float(4.6116860184274E+19) which is more or less correct but not very precise

// BigNumbers follow standard bool logic
$number = new BigNumber(0);
var_dump((bool) $number); // bool(false)

BigNumber allows standard mathematical operations with other BigNumbers, ints, floats, strings and objects implementing __toString() method. Operations always return a new instance of BigNumber.

<?php

use Rikudou\Units\Number\BigNumber;

$number = new BigNumber(10);

var_dump($number + $number); // BigNumber with value 20
var_dump($number + 10); // BigNumber with value 20
var_dump($number + 10.5); // BigNumber with value 20.5
var_dump($number + '10'); // BigNumber with value 20

$stringableObject = new class {
    public function __toString(): string {
        return '10';
    }
};

var_dump($number + $stringableObject); // BigNumber with value 20

These standard mathematical operations are supported on BigNumbers:

  • addition
  • subtraction
  • multiplication
  • division
  • exponentiation

Installation

composer require rikudou/units

Operations with units

All items of the same type can be freely added and subtracted. Additionally all units can be added, subtracted, multiplied and divided by numbers (BigNumber, string, int, float, stringable objects). Some units can also be multiplied and divided by other units where it makes sense (e.g. length units multiplied result in area units, area units divided by length units result in length units). Adding between unrelated units (like length and area) that don't make sense are not supported.

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Centimeter;

$meter = new Meter(1);
$centimeter = new Centimeter(10);

var_dump($meter + $centimeter); // 1.1 meters
var_dump($meter - $centimeter); // 0.9 meters
var_dump($meter * $centimeter); // 0.1 square meters
var_dump($meter / $centimeter); // error
var_dump($meter * 2); // 2 meters
var_dump($meter / 2); // 0.5 meters
var_dump($meter ** 2); // 1 square meter
var_dump($meter ** 3); // 1 cubic meter
var_dump($meter ** 4); // error

$squareMeter = $meter ** 2;
var_dump($squareMeter / $meter); // 1 meter
var_dump($squareMeter * $meter); // 1 cubic meter
var_dump($squareMeter * $squareMeter); // error
var_dump($squareMeter / $squareMeter); // error

$cubicMeter = $meter ** 3;
var_dump($cubicMeter / $squareMeter); // 1 meter
var_dump($cubicMeter / $meter); // 1 square meter

You can also freely work with units from different systems:

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Yard;

$meter = new Meter(1);
$yard = new Yard(1);

var_dump($meter + $yard); // 1.9144 meters
var_dump($meter - $yard); // 0.0856 meters
var_dump($meter * $yard); // 0.9144 square meters

var_dump($yard + $meter); // 2.0936132983377 yards

The order of operations matters as the first unit is the one result will be converted to. If you want to convert the result to different units you can use the UnitConverter object:

<?php

use Rikudou\Units\Converter\UnitConverter;
use Rikudou\Units\Unit\Length\Foot;
use Rikudou\Units\Unit\Length\Yard;
use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Temperature\Celsius;
use Rikudou\Units\Unit\Temperature\Fahrenheit;

$converter = new UnitConverter();

$yards = new Yard(10);
$feet = new Foot(10);

$result = $yards + $feet;
$meters = $converter->convert($result, Meter::class);
var_dump($meters); // 12.19199999999999 meters

$celsius = new Celsius(100);
var_dump($converter->convert($celsius, Fahrenheit::class)); // 212 fahrenheits

Supported Units

Length

  • millimeter
  • centimeter
  • meter
  • kilometer
  • inch
  • foot
  • yard
  • mile

Area

  • square millimeter
  • square centimeter
  • square meter
  • square kilometer
  • square foot
  • acre

Volume

  • cubic millimeter
  • cubic centimeter
  • cubic meter
  • cubic kilometer
  • cubic foot
  • litre
  • millilitre
  • centilitre
  • decilitre

Temperature

  • celsius
  • fahrenheit
  • kelvin

If you'd like another unit supported, please create an issue.

Comparing

You can compare related units together:

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Centimeter;
use Rikudou\Units\Unit\Temperature\Celsius;
use Rikudou\Units\Unit\Temperature\Fahrenheit;

$meter = new Meter(1);
$centimeters = new Centimeter(100);

var_dump($meter > $centimeters); // false
var_dump($meter < $centimeters); // false
var_dump($meter == $centimeters); // true
var_dump($meter >= $centimeters); // true
var_dump($meter <= $centimeters); // true

$celsius = new Celsius(100);
$fahrenheit = new Fahrenheit(100);

var_dump($celsius > $fahrenheit); // true

The same works for BigNumbers:

<?php

use Rikudou\Units\Number\BigNumber;

$number = new BigNumber(5);

var_dump($number > 4); // true
var_dump($number > 6); // false
var_dump($number > 4.5); // true
var_dump($number > '4'); // true
var_dump($number > new BigNumber(3)); // true

String Casting

When a unit is cast to a string, the value and unit is printed:

<?php

use Rikudou\Units\Unit\Length\Meter;
use Rikudou\Units\Unit\Length\Inch;
use Rikudou\Units\Unit\Length\Foot;

$meters = new Meter(5);
$metersSquared = $meters ** 2;
$metersCubic = $meters ** 3;
$inches = new Inch(5);
$feet = new Foot(3.5);

var_dump((string) $meters); // string(3) "5 m"
var_dump((string) $metersSquared); // string(6) "25 m²"
var_dump((string) $metersCubic); // string(7) "125 m³"
var_dump((string) $inches); // string(4) "5″"
var_dump((string) $feet); // string(8) "3′6″"

As you can see, the feet have a special casting where decimals are converted to inches.

You might also like...
Arbitrary-precision arithmetic library for PHP
Arbitrary-precision arithmetic library for PHP

Arbitrary-precision arithmetic library for PHP

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

vfsStream vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with

Basic calculator made in PHP, CSS3 and JavaScript.
Basic calculator made in PHP, CSS3 and JavaScript.

Basic Calculator in PHP Basic calculator in PHP made for treining. 👨‍💻 Used Technology PHP HTML CSS JavaScript 📝 License This project is under MIT

Changeset calculator between two states of a data

Totem \\\\//// |.)(.| | || | Changeset calculator between two state of a data \(__)/ Requires PHP 5.4 ; Compatible

PHP Class converter to namepaces.

Namespacer This tool will assist you in taking older underscore/prefix spaced code and will namespace it as best as it can, and also make the files an

HTML to PDF converter for PHP

Dompdf Dompdf is an HTML to PDF converter At its heart, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is

Arbitrary number base converter.

Numbase Easily convert numbers between arbitrary bases and symbol sets. Installation This library is available on Packagist as thunderer/numbase. It r

An ANSI to HTML5 converter

ANSI to HTML5 Converter This small library only does one thing: converting a text containing ANSI codes to an HTML5 fragment: require_once __DIR__.'/v

Laravel: Data to Monthly Converter

Laravel: Data to Monthly Converter Using this package you will be able to converts your collection using a timestamp field to order data monthly or ye

UUID = ULID bidirectional converter

uuid-ulid-converter UUID = ULID bidirectional converter Installing composer require mpyw/uuid-ulid-converter API static string Converter::uuidToUli

Google-like values converter

Google-like values converter. Support for different types of conversions, for examples: 1 kilometer - meters 1 dollar - THB 1 kilogram - meters ...

PHPUnit to Pest Converter

PestConverter PestConverter is a PHP library for converting PHPUnit tests to Pest tests. Before use Before using this converter, make sure your files

A full-featured home hosted Cloud Drive, Personal Assistant, App Launcher, File Converter, Streamer, Share Tool & More!
A full-featured home hosted Cloud Drive, Personal Assistant, App Launcher, File Converter, Streamer, Share Tool & More!

A Fully Featured home-hosted Cloud Storage platform and Personal Assistant that Converts files, OCR's images & documents, Creates archives, Scans for viruses, Protects your server, Keeps itself up-to-date, and Runs your own AppLauncher!

JavaScript to JQuery Converter

JQuery To Javascript Converter for helping to removing JQuery on websites.

The WordPress Categories to Tags Converter.

=== Categories to Tags Converter === Contributors: wordpressdotorg Donate link: Tags: importer, categories and tags converter Requires at least: 3.0

The modern, simple and intuitive PHP unit testing framework.

atoum PHP version atoum version 5.3 - 5.6 1.x - 3.x 7.2 - 8.x 4.x (current) A simple, modern and intuitive unit testing framework for PHP! Just lik

PHP unit testing framework with built in mocks and stubs. Runs in the browser, or via the command line.

Enhance PHP A unit testing framework with mocks and stubs. Built for PHP, in PHP! Quick Start: Just add EnhanceTestFramework.php and you are ready to

SimpleTest is a framework for unit testing, web site testing and mock objects for PHP

SimpleTest SimpleTest is a framework for unit testing, web site testing and mock objects for PHP. Installation Downloads All downloads are stored on G

Owner
Dominik Chrástecký
Dominik Chrástecký
Mark Rogoyski 2.2k Dec 29, 2022
Library for converting units and sizes in PHP

php-conversion Library for converting units and sizes in PHP. Units supported Acceleration Angle Area Digital information Electric current Frequency F

Christoffer Niska 127 Dec 23, 2022
Library for converting units and sizes in PHP

php-conversion Library for converting units and sizes in PHP. Units supported Acceleration Angle Area Digital information Electric current Frequency F

Christoffer Niska 122 Mar 16, 2021
Tensor is a library and extension that provides objects for scientific computing in PHP.

Tensor is a library and extension that provides objects for scientific computing in PHP. The multithreaded extension is especially suited for computing large sets of numbers. In some cases, the extension is 230X faster than the same operation in PHPland. Tensor is used by libraries such as Rubix ML to build and accelerate machine learning algorithms such as linear regression, dimensionality reduction, and neural networks.

Rubix 157 Jan 3, 2023
Library to parse, format and convert byte units

Byte Units This is a utility component for parsing, formatting, converting and manipulating byte units in various formats. Usage <?php // Bytes manip

Gabriele Lana 156 Dec 9, 2022
A library for handling physical quantities and the units of measure in which they're represented.

PHP Units of Measure master: Introduction This is a PHP library for representing and converting physical units of measure. The utility of this library

Jonathan Hanson 21 Sep 28, 2022
PHP version of Google's phone number handling library

libphonenumber for PHP What is it? A PHP library for parsing, formatting, storing and validating international phone numbers. This library is based on

Joshua Gigg 4.2k Jan 7, 2023
A PHP 5.3+ mathematics library, providing functionality for large numbers

Moontoast Math Library Moontoast\Math is useful for working with integers that are larger than (or may become larger than, through mathematical comput

Moontoast 245 Sep 8, 2022
Advanced Mathematics Library for PHP (port of Numbers.js)

Numbers.php Numbers.php - an advanced mathematics toolkit for PHP >= 5.3. It is a port of Numbers.js - same toolkit for JavaScript. There is a version

null 159 Jul 24, 2022
BigNum library for PHP compatible with bn.js

BigNum library for PHP Information This library provides a PHP Big Number API compatible with bn.js and is used in Fast PHP ECC library elliptic-php.

Simplito 16 Nov 13, 2022