@@ -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