1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\CLDR;
class Number
{
/**
* Returns the precision of a number.
*
* @param number $number
*
* @return int
*/
static public function precision_from($number)
{
$number = (string) $number;
$pos = strrpos($number, '.');
if (!$pos)
{
return 0;
}
return strlen($number) - $pos - 1;
}
/**
* Returns a number rounded to the specified precision.
*
* @param number $number
* @param int $precision
*
* @return float
*/
static public function round_to($number, $precision)
{
return round($number, $precision);
}
/**
* Parses a number.
*
* @param number $number
* @param null|int $precision
*
* @return array An array of [ $integer, $fractional ]. The fractional part is `null` if
* `$number` has no decimal separator.
*/
static public function parse($number, $precision = null)
{
if ($precision === null)
{
$precision = self::precision_from($number);
}
$number = self::round_to($number, $precision);
$number = abs($number);
$number = number_format($number, $precision, '.', '');
list($integer, $fractional) = explode('.', (string) $number) + [ 1 => null ];
return [ (int) $integer, $fractional ];
}
}