Skip to content

Commit 149d4c3

Browse files
committed
Added support for optional explicit BinarySuffix precision
1 parent 75825a8 commit 149d4c3

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

src/Coduo/PHPHumanizer/Number.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ public static function ordinal($number)
1919
return (string) new Ordinal($number);
2020
}
2121

22-
public static function binarySuffix($number, $locale = 'en')
22+
public static function binarySuffix($number, $locale = 'en', $precision = null)
2323
{
24-
$binarySuffix = new BinarySuffix($number, $locale);
24+
$binarySuffix = new BinarySuffix($number, $locale, $precision);
2525

2626
return $binarySuffix->convert();
2727
}

src/Coduo/PHPHumanizer/String/BinarySuffix.php

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,53 @@ class BinarySuffix
2929
);
3030

3131
/**
32-
* @param $number
33-
* @param string $locale
32+
* @param integer $number
33+
* @param string $locale
34+
* @param integer $precision
3435
*
3536
* @throws \InvalidArgumentException
3637
*/
37-
public function __construct($number, $locale = 'en')
38+
public function __construct($number, $locale = 'en', $precision = null)
3839
{
3940
if (!is_numeric($number)) {
4041
throw new \InvalidArgumentException('Binary suffix converter accept only numeric values.');
4142
}
4243

44+
if(!is_null($precision)){
45+
$this->setSpecificPrecisionFormat($precision);
46+
}
47+
4348
$this->number = (int) $number;
4449
$this->locale = $locale;
4550
}
4651

52+
/**
53+
* Replaces the default ICU 56.1 decimal formats defined in $binaryPrefixes with ones that provide the same symbols
54+
* but the provided number of decimal places
55+
*
56+
* @param integer $precision
57+
*
58+
* @throws \InvalidArgumentException
59+
*/
60+
protected function setSpecificPrecisionFormat($precision)
61+
{
62+
if($precision < 0){
63+
throw new \InvalidArgumentException('Precision must be positive');
64+
}
65+
if($precision > 3){
66+
throw new \InvalidArgumentException('Invalid precision. Binary suffix converter can only represent values in '.
67+
'up to three decimal places');
68+
}
69+
70+
$icuFormat = str_pad('#.', (2+$precision), '0');
71+
foreach ($this->binaryPrefixes as $size => $unitPattern) {
72+
if($size >= 1024){
73+
$symbol = substr($unitPattern, strpos($unitPattern, ' '));
74+
$this->binaryPrefixes[$size] = $icuFormat.$symbol;
75+
}
76+
}
77+
}
78+
4779
public function convert()
4880
{
4981
$formatter = new \NumberFormatter($this->locale, \NumberFormatter::PATTERN_DECIMAL);

0 commit comments

Comments
 (0)