PHP Classes

SI Prefix Converter: Convert a number to a string appending a prefix

Recommend this page to a friend!
  Info   View files Example   Demos   Screenshots Screenshots   View files View files (14)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2024-01-09 (5 months ago) RSS 2.0 feedNot enough user ratingsTotal: 145 All time: 9,141 This week: 560Up
Version License PHP version Categories
sci-convert 1.2GNU General Publi...5.3PHP 5, Conversion, Math


This class can convert a number to a string appending a prefix from the International System of Units (SI).

It can take a number and calculate its order of magnitude to determine what is the prefix to be appended to the number, for instance converting 250000 to 250K.

The conversion can be configured to define rounding rules, the numeric base, and the text of the prefixes.

In Spanish:

Esta clase permite hacer conversiones entre un numero (estÚ en un formato numerico o en un string) y su representaciˇn con prefijos en cualquier base. (ej, se puede convertir entre 250000 y 250K -prefijos SI- o 244.14Ki -prefijos binarios-)

Se puede crear un sistema personalizado (base y prefijos con sus valores) real o ficticio; guardando sus configuraciones en archivos distintos.

Realiza conversiones bidireccionales (de numero a formato con prefijos y de formato con prefijos a numero, siempre y cuando la codificaciˇn estÚ configurada correctamente), y se puede ajustar el modo de redondeo (decimales o cifras significativas) para la conversion hacia prefijos. Tambien se puede escoger si se quiere el numero resultante, unido al prefijo; o por aparte para darle un tratamiento independiente a ambas partes.

Innovation Award
PHP Programming Innovation award nominee
June 2014
Number 6

Prize: One downloadable copy of Komodo IDE
Sometimes it is necessary to display numbers in an abbreviated format.

This class provides a solution that can abbreviate numbers by appending prefixes like KB, MB, GB, TB, etc..

Manuel Lemos
Picture of Alex F. Bustos
  Performance   Level  
Name: Alex F. Bustos <contact>
Classes: 1 package by
Country: Colombia Colombia
Age: 29
All time rank: 428529 in Colombia Colombia
Week rank: 234 Up3 in Colombia Colombia Up
Innovation award
Innovation award
Nominee: 1x


<?php echo '<!DOCTYPE html>' ?>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing of the "sci" Class</title>
 * File: examples.php
 * Author: Alex F. Bustos - alexfbp at gmail dot com
 * Non required file. Feel free to delete/hide/block...
 * I suggest you first to open the browser output of this.
 * Then, if you have curiosity; open again this file.
include (

'Default settings (ENG mode, 3 significant digits, base 10) and HTML List of Prefixes (LOP)'.PHP_EOL;
$sci1=new sci('si_short_html');

//number - scale
' -5486800', //1M
54860, //100K
'-54868', //10K
'+5486.8', //1K
-548.68, //100
'+54.868', //10
' -5.4868 ', //1
'+.54868', //100m
'-.054868', //10m
'+.0054868', //1m
' -.00054868 ', //100u
'+.000054868', //10u
' +.000054868' //1u

foreach (
$array as $test) {
'"',(string) $test,'" : ';

PHP_EOL.'Same Example, but in decimal mode (no significant digits)'.PHP_EOL;


foreach (
$array as $test) {
'"',(string) $test,'" : ';

PHP_EOL.'<u>Output Recognition</u> - Maybe you first should choose the right charset through
the set_charset() function or modifying the settings file.'

'Example taking the HTML output (view the source code and note that the choosen LOP was si_short_html)'.PHP_EOL;

PHP_EOL.'Example with special character in the string. If you changed the encoding of this
file (perhaps simply by the fact of having edited), maybe this example won\'t work.'
try {
var_dump($sci1->get_number('20┬Á┬Á')); //20micromicro
} catch (Exception $e) {
'Error Found: ',$e->getMessage(),PHP_EOL;

PHP_EOL.'<u>Example with base change:</u>'.PHP_EOL;
//$sci2=new sci('binary_short',2,0,40); //old example
//$sci2=new sci('binary_short',null,null,null); //new, but equivalent to:
$sci2=new sci('binary_short');

PHP_EOL.'"Usually in MS Windows, a drive with '.$size.'B would be informed as an unit of '.$sci1->get_prefixed($size).'B,
but when you look in some Linux distros, it will appear simply as an unit of '

PHP_EOL.'Example becoming independent the number and prefix:'.PHP_EOL;
'<em>"The last voltage measuring was of '.$result[0].' <strong style="color: red;">'.$result[1].'V</strong>"</em>

//"numeric part" - "prefix part" -> result
'1.2Mp', //"1.2" - "Mp" -> ok
'1 kk', //"1" - " kk" -> ok
'-1┬Á ┬Á', //"-1" - "┬Á ┬Á" -> ok if charset ok.
'2e3km', //"2e3" - "km" ->ok
'4E5 m', //"4E5" - " m" ->ok
'2 E k', //"2" -> "Ek" -> Error->Exception. The E are not a prefix.
'k'); //Can also be used the prefix alone

echo PHP_EOL.'<u>Processing of Multiple Prefixes</u>
Suppose that you have a field in wich you\'re asking for a capacitor value in
picofarads (pF), and someone wants to use a capacitor of 1&micro;F. That are,
also, 1\'000.000 of pF. But, why introduce that if you could use simply the
"1M" value?

Other similar example are when you are asking a resistor value in K&Omega; and
someone wants to use a 1M&Omega; resistor, that are an 1000K&Omega; resistor.
Again, why to insert the 1000 when you can insert 1K?

That class allows the simplification of prefixes, knowing that a prefix are
an abbreviation of a multiplication by another number.

There are both and additional samples (intentional error in the penultimate string - see the source code):'
$examples as $key => $example) {
'"'.$example.'" : ';
    try {
'$sci->get_number($examples['.$key.']) = $sci->get_number('.htmlentities($example,ENT_COMPAT,'UTF-8').') = ',
$aux=$sci1->get_number($example)).' = '.$sci1->get_prefixed($aux).PHP_EOL;
    } catch (
Exception $e){
'Error Found (',$e->getCode(),'): ',$e->getMessage(),PHP_EOL;
Note that in $examples[3] the string was '
.$examples[3].', which has a float number (2e3).
It means that if you don\'t want to write 2000 as 2K, but 2e3 or 2E3; you can do it also.
That behaviour are system dependant (string to -numeric format, probably float- conversion)

What happened with $examples[5]?
Supoose that you have a LOP conformed by "foo", "e" and other prefixes.
If you insert a number, as example "2e3foo" the class will recognize the numeric part as "2e3"
and the prefixed part as "foo" other example, "2efoo" will recognize the numeric part as "2"
and the prefix part as "efoo". This because the prefix part are recognized analyzing the string
from right to left and, note that the prefix part are case-sensitive.'

The string that you could be viewing as the assigned value for $examples[2] should
be something like "-1u u", where each \'u\' are, or the micro or the mu character.

Don\'t forget to set up the encoding format, in both parts:
->In the head of the HTML document; through the meta tag:'
.PHP_EOL.' '.
htmlentities('<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />').
->In the configuration of the class, through the __construct() or set_charset() functions.

1. Copy the output of your browser of one of this characters: micro (&micro;) or mu (&mu;)
2. Paste as the argument of the function inside the next "try-catch" block
   (edit the source code to see it):
try {
var_dump($sci1->get_number('1┬Á┬Á')); //2. Change each of the 'u's by the copied character
} catch (Exception $e) {
'Error Found: ',$e->getMessage(),PHP_EOL;
echo 'Repeat until it stops giving exceptions and returns a number.</pre></body></html>';


File: readme.txt Created by: Alex Bustos - @alexfbp At first, Thanks for downloading and testing it. This file is a little resume and explanation on how to use this class. For specific details, see the class and demo files. ======================================= INITIALIZATION STEPS 1. Include, instantiate and (opt) set the numeric and list limitations include(''); //Maybe you want to change some default values include('sci.class.php'); $sci=new sci('LOP'[,- more options-]); //See the __construct() function for details. If the first argument of the construct is a variable, you must be sure that this variable is sanitized, has not forbidden expressions such as "..", "/", etc... The 'LOP' (List Of Prefixes) are the DESIRED list, not the used list which are generated internally through a call to the start() function (step 4) 2. (opt) Set the numeric out format. By decimal places or significant digits $sci->set_round_params(); 3. (opt) Insert Additive Rules $sci->set_single_rule(); $sci->set_scale_rule(); $sci->set_all_rule(); 4. $sci->start(); //the object. Else, the main functions will return the unmodified value ======================================= MAIN FUNCTIONS: mixed get_prefixed(mixed $value,bool $array=false): Returns a string like $number.$join.$prefix. based on a previously choosen List of Prefixes. The $join value was previously defined when instantiating the object. Or, if you want to format the prefix as you want, you can set $array=true, and the function will return an array($number,$prefix); mixed get_number(string $string, bool $entities=true, $flags=ENT_COMPAT) If you want to do the inverse process, here comes that function. May return a float or a int. Prior to use this function, you should configure the charset. ======================================= CONFIGURATION FUNCTIONS: sci::valid_list($LOP) - Basic validation if a List of Prefixes $LOP are in the allowed format. set_round_params() - Rounding Configuration. See the class and then set_charset($charset) - Valid Charset. See the $encoding arg of ======================================= RULE FUNCTIONS: Add to the ALLOWED list, from the DESIRED list (and if the exponent are valid in the specified range): set_single_rule($exponent); //a prefix of the same exponent set_scale_rule($scale); //each prefix multiple of $scale Omitting the limits, ej: with 3, allowed exps will have too {...,-9,-6,-3,0,3,6,9,...} with 2, allowed exps will have too {...,-6,-4,-2,0,2,4,6,...} and so... set_all_rule(); //All of the prefixes If needed, to understand the differences between the allowed and desired lists, var_dump an sci object, before and after to the call to start(): $sci=new sci(); var_dump($sci); ... //Maybe you wish to add some rules $sci->start(); var_dump($sci);

  Example includedExternal page  

Open in a separate window

  • screenshot_example.png
  Files folder image Files  
File Role Description
Files folder imagesets (10 files)
Plain text file sci.class.php Class Main class
Accessible without login Plain text file examples.php Example Many possible uses of the class
Accessible without login Plain text file README.txt Doc. Brief of how to use the class
Accessible without login Plain text file Conf. Default settings of the class

  Files folder image Files  /  sets  
File Role Description
  Accessible without login Plain text file binary_long.set.php Aux. Binary prefixes in long format
  Accessible without login Plain text file binary_short.set.php Aux. Binary prefixes in short format
  Accessible without login Plain text file README.txt Doc. Considerations about the Lists of prefixes
  Accessible without login Plain text file sets-README.txt Doc. Documentation
  Accessible without login Plain text file si_long.set.php Aux. SI prefixes in long format
  Accessible without login Plain text file si_long_es.set.php Aux. Copy of "long", but changing the 10e-3 prefix to mili
  Accessible without login Plain text file si_short.set.php Aux. SI prefixes in short format
  Accessible without login Plain text file si_short_html.set.php Aux. SI prefixes in short format and HTML entities for micro
  Accessible without login Plain text file si_short_strict.set.php Aux. Introduced in 1.2, according wit the CGPM
  Accessible without login Plain text file si_short_strict_html.set.php Aux. Introduced in 1.2, according wit the CGPM

 Version Control Unique User Downloads Download Rankings  
This week:0
All time:9,141
This week:560Up