-
Notifications
You must be signed in to change notification settings - Fork 78
/
fNumber.php
1634 lines (1343 loc) · 44.6 KB
/
fNumber.php
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Provides large/precise number support
*
* @copyright Copyright (c) 2008-2011 Will Bond
* @author Will Bond [wb] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fNumber
*
* @version 1.0.0b3
* @changes 1.0.0b3 Added the `$remove_zero_fraction` parameter to ::format() [wb, 2011-02-02]
* @changes 1.0.0b2 Fixed a bug with parsing decimal numbers in scientific notation [wb, 2010-04-13]
* @changes 1.0.0b The initial implementation [wb, 2008-07-21]
*/
class fNumber
{
// The following constants allow for nice looking callbacks to static methods
const baseConvert = 'fNumber::baseConvert';
const pi = 'fNumber::pi';
const registerFormatCallback = 'fNumber::registerFormatCallback';
const registerUnformatCallback = 'fNumber::registerUnformatCallback';
const reset = 'fNumber::reset';
/**
* A callback to process all values through
*
* @var callback
*/
static private $format_callback = NULL;
/**
* A callback to process all values through
*
* @var callback
*/
static private $unformat_callback = NULL;
/**
* Converts any positive integer between any two bases ranging from `2` to `16`
*
* @param fNumber|string $number The positive integer to convert
* @param integer $from_base The base to convert from - must be between `2` and `16`
* @param integer $to_base The base to convert to - must be between `2` and `16`
* @return string The number converted to the new base
*/
static public function baseConvert($number, $from_base, $to_base)
{
if ($number instanceof fNumber && $from_base != 10) {
throw new fProgrammerException(
'The from base specified, %s, is not valid for an fNumber object',
$from_base
);
}
if (strlen($number) && $number[0] == '+') {
$number = substr($number, 1);
}
if (!ctype_xdigit($number)) {
throw new fProgrammerException(
'The number specified, %s, does not appear to be a positive integer. Negative numbers and fractions are not supported due the different encoding schemes that can be used.',
$number
);
}
if (!is_numeric($from_base) || $from_base < 2 || $from_base > 16) {
throw new fProgrammerException(
'The from base specified, %1$s, is not valid base between %2$s and %3$s',
$from_base,
'2',
'16'
);
}
if (!is_numeric($to_base) || $to_base < 2 || $to_base > 16) {
throw new fProgrammerException('The to base specified, %1$s, is not valid base between %2$s and %3$s',
$from_base,
'2',
'16'
);
}
$base_string = '0123456789ABCDEF';
$base_map = array(
'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15
);
/* Convert input number to base 10 */
if ($from_base != 10) {
$length = strlen($number);
$decimal = new fNumber('0');
$base_num = new fNumber($from_base);
for($i = 0; $i < $length; $i++) {
$char = strtoupper($number[$i]);
$value = new fNumber((isset($base_map[$char])) ? $base_map[$char] : $char);
$decimal = $decimal->add($value->mul($base_num->pow($length-($i+1)))->round(0));
}
} elseif (!$number instanceof fNumber) {
$decimal = new fNumber($number);
} else {
$decimal = $number;
}
$output = '';
if ($to_base != 10) {
do {
$frac = $decimal->div($to_base, 3)->__toString();
$frac = '0' . substr($frac, strpos($frac, '.'));
$x = (int) ($frac * $to_base + 1.5);
$output = $base_string[$x-1] . $output;
$decimal = $decimal->div($to_base, 0);
} while($decimal->gt('0.0'));
} else {
$output = $decimal->__toString();
}
return $output;
}
/**
* Compared the two numbers
*
* @param string $number1 The first number to compare
* @param string $number2 The second number to compare
* @return integer Less than `0` if `$number1` is less than `$number2`, `0` if equal, greater than `0` if `$number1` is greater than `$number2`
*/
static private function cmp($number1, $number2)
{
$number1 = self::fixSign($number1);
$number2 = self::fixSign($number2);
if ($number1[0] != $number2[0]) {
return ($number1[0] == '+') ? 1 : -1;
}
if ($number1[0] == '-') {
return strnatcmp(substr($number2, 1), substr($number1, 1));
} else {
return strnatcmp(substr($number1, 1), substr($number2, 1));
}
}
/**
* Makes sure a number has a sign
*
* @param string $number The number to check
* @return string The number with a sign
*/
static private function fixSign($number)
{
$number = (string) $number;
if (ctype_digit($number[0])) {
$number = '+' . $number;
}
return $number;
}
/**
* Checks to see if a number is equal to zero
*
* @param string $number The number to check, first character should be the sign
* @return boolean If the number is equal to zero
*/
static private function isZero($number)
{
return trim(substr(str_replace('.', '', $number), 1), '0') == '';
}
/**
* Normalizes two numbers to the same number of decimal places
*
* @throws fValidationException When `$number1` or `$number2` is not a valid number
*
* @param fNumber|string $number1 The first number to normalize
* @param fNumber|string $number2 The second number to normalize
* @param integer $scale The number of decimal places to normalize to
* @return array The two normalized numbers as strings
*/
static private function normalize($number1, $number2, $scale=NULL)
{
$number1 = self::parse($number1, 'array');
$number2 = self::parse($number2, 'array');
if ($scale !== NULL || $number1['fraction'] || $number2['fraction']) {
if ($scale === NULL) {
$frac_len = max(strlen($number1['fraction']), strlen($number2['fraction']));
} else {
$frac_len = $scale;
}
if ($scale !== NULL && strlen($number1['fraction']) > $scale) {
$number1['fraction'] = substr($number1['fraction'], 0, $scale);
} else {
$number1['fraction'] = str_pad($number1['fraction'], $frac_len, '0', STR_PAD_RIGHT);
}
if ($scale !== NULL && strlen($number2['fraction']) > $scale) {
$number2['fraction'] = substr($number2['fraction'], 0, $scale);
} else {
$number2['fraction'] = str_pad($number2['fraction'], $frac_len, '0', STR_PAD_RIGHT);
}
$number1 = join('.', $number1);
$number2 = join('.', $number2);
} else {
$number1 = $number1['integer'];
$number2 = $number2['integer'];
}
$len = max(strlen($number1)-1, strlen($number2)-1);
$number1 = $number1[0] . str_pad(substr($number1, 1), $len, '0', STR_PAD_LEFT);
$number2 = $number2[0] . str_pad(substr($number2, 1), $len, '0', STR_PAD_LEFT);
return array($number1, $number2);
}
/**
* Parses a number to ensure it is valid
*
* @throws fValidationException When `$number` is not a valid number
*
* @param object|string $number The number to parse
* @param string $element The element to return: `'number'`, `'integer'`, `'fraction'`, `'array'`
* @return mixed The requested parsed element
*/
static private function parse($number, $element)
{
if (is_object($number) && is_callable(array($number, '__toString'))) {
$number = $number->__toString();
} else {
$number = (string) $number;
}
$number = trim($number);
if (self::$unformat_callback) {
$number = call_user_func(self::$unformat_callback, $number);
} else {
$number = str_replace(',', '', $number);
}
$matched = preg_match('#^([+\-]?)((?:\d*\.)?\d+)(?:e([+\-]?)(\d+))?$#iD', $number, $matches);
if (!$matched) {
throw new fValidationException(
'The number specified, %s, is invalid.',
$number
);
}
// Determine the sign
$sign = ($matches[1] == '-') ? '-' : '+';
$number = self::stripLeadingZeroes($matches[2]);
$exponent = (isset($matches[4])) ? $matches[4] : NULL;
$exponent_sign = (isset($matches[3])) ? $matches[3] : NULL;
// Adjust the number by the exponent
if ($exponent) {
// A negative exponent means bringing the decimal to the left
if ($exponent_sign == '-') {
$decimal_pos = strpos($number, '.');
if ($decimal_pos === FALSE) {
$fraction = '';
$integer = $number;
} else {
$fraction = substr($number, strpos($number, '.')+1);
$integer = substr($number, 0, strpos($number, '.'));
}
if (strlen($integer) < $exponent) {
$before_decimal = '0';
$after_decimal = str_pad($integer, $exponent, '0', STR_PAD_LEFT);
} else {
$break_point = strlen($integer)-$exponent;
$before_decimal = substr($integer, 0, $break_point);
$after_decimal = substr($integer, $break_point);
}
$number = $before_decimal . '.' . $after_decimal . $fraction;
// A positive exponent means extending the number to the right
} else {
$number .= str_pad('', $exponent, '0', STR_PAD_RIGHT);
}
}
// Strip any leading zeros that may have been added
$number = self::stripLeadingZeroes($number);
if (self::isZero($sign . $number)) {
$sign = '+';
}
$parts = explode('.', $sign . $number);
$output = array();
$output['integer'] = $parts[0];
$output['fraction'] = (isset($parts[1])) ? $parts[1] : '';
if ($element == 'integer') {
return $output['integer'];
}
if ($element == 'fraction') {
return $output['fraction'];
}
if ($element == 'array') {
return $output;
}
return join('.', $parts);
}
/**
* Adds two numbers together
*
* @throws fValidationException When `$number1` or `$number2` is not a valid number
*
* @param string $number1 The first addend
* @param string $number2 The second addend
* @param integer $scale The number of digits after the decimal
* @return string The sum of the two numbers
*/
static private function performAdd($number1, $number2, $scale=NULL)
{
list($number1, $number2) = self::normalize($number1, $number2);
if (self::isZero($number1)) {
return self::setScale($number2, $scale);
} elseif (self::isZero($number2)) {
return self::setScale($number1, $scale);
}
// If the two numbers differ in sign, we need to subtract instead
if ($number1[0] != $number2[0]) {
if ($number1[0] == '-') {
return self::performSub($number2, '+' . substr($number1, 1));
}
return self::performSub($number1, '+' . substr($number2, 1));
}
$carry = 0;
$output = '';
for ($i=strlen($number1)-1; $i>0; $i--) {
if ($number1[$i] == '.') {
$output = '.' . $output;
continue;
}
$sum = $number1[$i] + $number2[$i] + $carry;
$carry = (strlen($sum) > 1) ? substr($sum, 0, -1) : 0;
$output = substr($sum, -1) . $output;
}
if ($carry) {
$output = $carry . $output;
}
$output = self::setScale($number1[0] . $output, $scale);
return self::stripLeadingZeroes($output);
}
/**
* Divides a number by another
*
* @throws fValidationException When `$dividend` or `$divisor` is not a valid number
*
* @param string $dividend The number to be divided
* @param string $divisor The number to divide by
* @param integer &$remainder The remainder from the division
* @param integer $scale The number of digits to return after the decimal
* @return string The quotient
*/
static private function performDiv($dividend, $divisor, &$remainder=NULL, $scale=NULL)
{
list ($dividend, $divisor) = self::normalize($dividend, $divisor);
$dividend = self::stripLeadingZeroes($dividend);
$divisor = self::stripLeadingZeroes($divisor);
if (self::isZero($dividend)) {
$remainder = '+0';
return self::setScale('+0', $scale);;
}
if (self::isZero($divisor)) {
throw new fValidationException(
'The divisor specified, %s, is zero, which is an invalid divisor',
$divisor
);
}
$sign = ($dividend[0] == $divisor[0]) ? '+' : '-';
$after_decimal = 0;
if (strpos($dividend, '.') !== FALSE) {
$dividend = str_replace('.', '', $dividend);
$divisor = str_replace('.', '', $divisor);
}
// Here we make sure we can divide the dividend at least once
if ($scale !== NULL) {
for ($i=0; $i < $scale; $i++) {
$dividend .= '0';
$after_decimal++;
}
}
if (strlen($dividend) < strlen($divisor)) {
$remainder = $dividend;
return self::setScale('+0', $scale);
}
// Perform multiplication using Knuth's algorithm from Art of Computer Science Vol 2
$u = '+' . substr($dividend, 1);
$v = '+' . substr($divisor, 1);
$n = strlen($v) - 1;
$m = (strlen($u) - 1) - $n;
// This is for single digit divisors
if ($n == 1) {
$n = strlen($u) - 1;
$w = $sign . str_pad('', $n, '0');
$r = 0;
$j = 1;
while ($j <= $n) {
$w[$j] = floor((($r*10)+$u[$j])/$v[1]);
$r = (($r*10)+$u[$j]) % $v[1];
$j++;
}
$quotient = $w;
$remainder = '+' . $r;
// This is for multi-digit divisors
} else {
$quotient = '0' . str_pad('', $m, '0');
// Step D1
$d = floor(10/($v[1] + 1));
$u = self::performMul($u, $d);
$v = self::performMul($v, $d);
if (strlen($u) == strlen($dividend)) {
$u = '0' . substr($u, 1);
} else {
$u = substr($u, 1);
}
// Step D2
$j = 0;
while ($j <= $m) {
// Step D3
$uj1 = (isset($u[$j+1])) ? $u[$j+1] : '0';
if ($u[$j] == $v[1]) {
$q = 9;
} else {
$q = floor((($u[$j]*10)+$uj1)/$v[1]);
}
$uj2 = (isset($u[$j+2])) ? $u[$j+2] : '0';
if ($v[2] * $q > (($u[$j]*10)+$uj1-($q*$v[1]))*10 + $uj2) {
$q -= 1;
if ($v[2] * $q > (($u[$j]*10)+$uj1-($q*$v[1]))*10 + $uj2) {
$q -= 1;
}
}
// Step D4
$ujn = self::performSub(substr($u, $j, $n+1), self::performMul($q, $v));
while (strlen($ujn)-1 < $n+1) {
$ujn = $ujn[0] . '0' . substr($ujn, 1);
}
while (strlen($ujn)-1 > $n+1) {
$ujn = $ujn[0] . substr($ujn, 2);
}
$borrow = FALSE;
if ($ujn[0] == '-') {
$ujn = self::performAdd(self::performPow('10', $n+1), $ujn);
$borrow = TRUE;
}
while (strlen($ujn)-1 > $n+1) {
$ujn = $ujn[0] . substr($ujn, 2);
}
// Step D5
if ($borrow) {
// Step D6
$q--;
$ujn = substr(self::performAdd($v, $ujn), 1);
}
$u = substr($u, 0, $j) . substr($ujn, 1) . substr($u, $j+$n+1);
$quotient[$j] = $q;
// Step D7
$j++;
}
$remainder = self::performDiv(substr($u, 1+$m, $n), $d);
}
if (strlen($quotient) < $after_decimal) {
$quotient = str_pad($quotient, $after_decimal+1, '0', STR_PAD_LEFT);
}
$integer = substr($quotient, 0, strlen($quotient)-$after_decimal);
$fraction = substr($quotient, strlen($quotient)-$after_decimal);
$fraction = (strlen($fraction)) ? '.' . $fraction : '';
$quotient = $integer . $fraction;
$quotient = self::stripLeadingZeroes($quotient);
if (ctype_digit($quotient[0])) {
$quotient = $sign . $quotient;
}
return $quotient;
}
/**
* Multiplies two numbers
*
* @param string $multiplicand The number to be multiplied
* @param string $multiplier The number of times to multiply the multiplicand
* @param integer $scale The number of digits after the decimal
* @return string The product
*/
static private function performMul($multiplicand, $multiplier, $scale=NULL)
{
$multiplicand = (string) $multiplicand;
$multiplier = (string) $multiplier;
$multiplicand = self::fixSign($multiplicand);
$multiplier = self::fixSign($multiplier);
if (self::isZero($multiplicand) || self::isZero($multiplier)) {
return self::setScale('+0', $scale);
}
$after_decimal = 0;
if (strpos($multiplicand, '.') !== FALSE) {
$after_decimal += strlen($multiplicand) - (strpos($multiplicand, '.') + 1);
$multiplicand = str_replace('.', '', $multiplicand);
}
if (strpos($multiplier, '.') !== FALSE) {
$after_decimal += strlen($multiplier) - (strpos($multiplier, '.') + 1);
$multiplier = str_replace('.', '', $multiplier);
}
// Perform multiplication using Knuth's algorithm from Art of Computer Science Vol 2
$n = strlen($multiplicand) - 1;
$m = strlen($multiplier) - 1;
$product = $multiplier . str_pad('', $n, '0');
$product[0] = ($multiplicand[0] == $multiplier[0]) ? '+' : '-';
$j = $m;
while ($j > 0) {
if ($multiplier[$j] == '0') {
$product[$j] = '0';
}
$i = $n;
$k = 0;
while ($i > 0) {
$t = ($multiplicand[$i] * $multiplier[$j]) + $product[$i+$j] + $k;
$product[$i+$j] = $t % 10;
$k = (int) $t/10;
--$i;
}
$product[$j] = $k;
--$j;
}
$integer = substr($product, 0, strlen($product)-$after_decimal);
$fraction = substr($product, strlen($product)-$after_decimal);
$fraction = (strlen($fraction)) ? '.' . $fraction : '';
$product = $integer . $fraction;
$product = self::setScale($product, $scale);
$product = self::stripLeadingZeroes($product);
return $product;
}
/**
* Calculates the integer power of a number
*
* @throws fValidationException When `$number` or `$power` is not a valid number or when `$power` is outside of the normal 32-bit integer range
*
* @param string $number The number to raise to the power
* @param string $power The power to raise to, must be between `−2,147,483,648` and `2,147,483,647`
* @return string The product
*/
static private function performPow($number, $power, $scale=NULL)
{
$number = self::fixSign($number);
$power = self::fixSign($power);
if (self::cmp($power, '-2147483648') < 0 || self::cmp($power, '+2147483647') > 0) {
throw new fValidationException(
'The power specified, %1$s, is beyond the range of supported powers. Only powers between %2$s and %3$s are supported.',
$power,
'-2147483648',
'2147483647'
);
}
if (self::isZero($power)) {
return '+1';
}
$negative_power = $power[0] == '-';
$power = '+' . substr($power, 1);
if ($power%2 == 0) {
$product = self::performPow(self::performMul($number, $number), $power/2);
} else {
$product = self::performMul($number, self::performPow(self::performMul($number, $number), floor($power/2)));
}
if ($negative_power) {
$product = self::performDiv('+1', $product, $trash, $scale);
}
$product = self::setScale($product, $scale);
return $product;
}
/**
* Subtracts the second number from the first
*
* @throws fValidationException When `$minuend` or `$subtrahend` is not a valid number
*
* @param string $minuend The number to subtract from
* @param string $subtrahend The number to subtract
* @return string The difference
*/
static private function performSub($minuend, $subtrahend, $scale=NULL)
{
list($minuend, $subtrahend) = self::normalize($minuend, $subtrahend);
if ($subtrahend[0] == '-') {
// If both are negative we are really subtracting the minuend from the subtrahend
if ($minuend[0] == '-') {
return self::performSub('+' . substr($subtrahend, 1), '+' . substr($minuend, 1), $scale);
}
// If the minuend is positive we are just doing an addition
return self::performAdd('+' . substr($subtrahend, 1), '+' . substr($minuend, 1), $scale);
}
// When the minuend is negative and the subtrahend positive, they are added
if ($minuend[0] == '-') {
$sum = self::performAdd('+' . substr($minuend, 1), $subtrahend, $scale);
return '-' . substr($sum, 1);
}
// If the subtrahend is bigger than the minuend, we reverse the
// subtraction and reverse the sign of the minuend
if (self::cmp($minuend, $subtrahend) < 0) {
$diff = self::performSub('+' . substr($subtrahend, 1), '+' . substr($minuend, 1), $scale);
$diff = substr($diff, 1);
return ($minuend[0] == '+') ? '-' . $diff : '+' . $diff;
}
$borrow = 0;
$output = '';
for ($i=strlen($minuend)-1; $i>0; $i--) {
if ($minuend[$i] == '.') {
$output = '.' . $output;
continue;
}
$diff = $minuend[$i] - $subtrahend[$i] - $borrow;
$borrow = 0;
while ($diff < 0) {
$borrow += 1;
$diff += 10;
}
$output = $diff . $output;
}
$output = self::setScale($minuend[0] . $output, $scale);
return self::stripLeadingZeroes($output);
}
/**
* Returns the value for pi with a scale of up to 500
*
* @param integer $scale The number of places after the decimal to return
* @return fNumber Pi
*/
static public function pi($scale)
{
static $pi_places = '14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912';
if (is_numeric($scale)) {
$scale = (int) $scale;
}
if (!is_numeric($scale) || $scale < 0 || $scale > 500) {
throw new fProgrammerException(
'The scale specified, %1$s, is outside the valid scale for pi (%2$s to %3$s)',
$scale,
'0',
'500'
);
}
$fraction = substr($pi_places, 0, $scale);
$fraction = (strlen($fraction)) ? '.' . $fraction : '';
return new fNumber('3' . $fraction);
}
/**
* Allows setting a callback to translate or modify any return values from ::format()
*
* The callback should accept two parameters:
* - `$value`: the string value of the number
* - `$remove_zero_fraction`: a boolean indicating if a zero fraction should be removed
*
* The callback should return a string, the formatted `$value`.
*
* @param callback $callback The callback to pass the fNumber value to - see method description for parameters
* @return void
*/
static public function registerFormatCallback($callback)
{
if (is_string($callback) && strpos($callback, '::') !== FALSE) {
$callback = explode('::', $callback);
}
self::$format_callback = $callback;
}
/**
* Allows setting a callback to clean any formatted values so they can be properly parsed - useful for languages where `,` is used as the decimal point
*
* @param callback $callback The callback to pass formatted strings to. Should accept a formatted string and return a string the is a valid number using `.` as the decimal point.
* @return void
*/
static public function registerUnformatCallback($callback)
{
if (is_string($callback) && strpos($callback, '::') !== FALSE) {
$callback = explode('::', $callback);
}
self::$unformat_callback = $callback;
}
/**
* Resets the configuration of the class
*
* @internal
*
* @return void
*/
static public function reset()
{
self::$format_callback = NULL;
self::$unformat_callback = NULL;
}
/**
* Sets the scale for a number
*
* @param string $number The number to set the scale for
* @param integer $scale The number of digits to have after the decimal
* @return string The scaled number
*/
static private function setScale($number, $scale)
{
if ($scale === NULL) {
return $number;
}
$parts = explode('.', $number);
$integer = $parts[0];
$fraction = (isset($parts[1])) ? $parts[1] : '';
if (strlen($fraction) > $scale) {
$fraction = substr($fraction, 0, $scale);
} else {
$fraction = str_pad($fraction, $scale, '0', STR_PAD_RIGHT);
}
$fraction = (strlen($fraction)) ? '.' . $fraction : '';
return $integer . $fraction;
}
/**
* Strips the leading zeroes off of a number
*
* @param string $number The number to strip
* @return string The number with leading zeroes stripped
*/
static private function stripLeadingZeroes($number)
{
$number = (string) $number;
if (ctype_digit($number[0]) || $number[0] == '.') {
$sign = '';
} else {
$sign = $number[0];
$number = substr($number, 1);
}
$number = ltrim($number, '0');
if (strlen($number) == 0 || $number[0] == '.') {
$number = '0' . $number;
}
return $sign . $number;
}
/**
* The scale (number of digits after the decimal) of the number
*
* @var integer
*/
private $scale;
/**
* The value of the number
*
* @var string
*/
private $value;
/**
* Creates a large/precise number
*
* @throws fValidationException When `$value` is not a valid number
*
* @param string $value The value for the number - any valid PHP integer or float format including values with `e` exponents
* @param integer $scale The number of digits after the decimal place, defaults to number of digits in `$value`
* @return fNumber
*/
public function __construct($value, $scale=NULL)
{
$value = self::parse($value, 'array');
if ($scale !== NULL) {
if (strlen($value['fraction']) > $scale) {
$value['fraction'] = substr($value['fraction'], 0, $scale);
} else {
$value['fraction'] = str_pad($value['fraction'], $scale, '0', STR_PAD_RIGHT);
}
}
$this->value = (strlen($value['fraction'])) ? join('.', $value) : $value['integer'];
$this->scale = strlen($value['fraction']);
}
/**
* All requests that hit this method should be requests for callbacks
*
* @internal
*
* @param string $method The method to create a callback for
* @return callback The callback for the method requested
*/
public function __get($method)
{
return array($this, $method);
}
/**
* Converts the object to an string
*
* @return string
*/
public function __toString()
{
return ($this->value[0] == '+') ? substr($this->value, 1) : $this->value;
}
/**
* Returns the absolute value of this number
*
* @param integer $scale The number of places after the decimal - overrides the scale for this number
* @return fNumber The absolute number
*/
public function abs($scale=NULL)
{
$scale = $this->fixScale($scale);
return new fNumber(substr($this->value, 1), $scale);
}
/**
* Adds two numbers together
*
* @throws fValidationException When `$addend` is not a valid number
*
* @param fNumber|string $addend The addend
* @param integer $scale The number of places after the decimal - overrides the scale for this number
* @return fNumber The sum
*/
public function add($addend, $scale=NULL)
{
$scale = $this->fixScale($scale);
$addend = self::parse($addend, 'number');
if (function_exists('bcadd')) {
$sum = bcadd($this->value, $addend, $scale);
} else {
$sum = self::performAdd($this->value, $addend, $scale);
}
return new fNumber($sum, $scale);
}
/**
* Rounds the number to the next highest integer
*
* @return fNumber The next highest integer
*/
public function ceil()
{
if (strpos($this->value, '.') === FALSE) {
return clone $this;
}
$fraction = substr($this->value, strpos($this->value, '.')+1);
$integer = substr($this->value, 0, strpos($this->value, '.'));
// Negative numbers or numbers with only 0 after the decimal can be truncated
if (trim($fraction, '0') === '' || $this->value[0] == '-') {
return new fNumber($integer);
}
// Positive numbers with a fraction need to be increased
return new fNumber(self::performAdd($integer, '1'));
}
/**
* Divides this number by the one passed
*
* @throws fValidationException When `$divisor` is not a valid number
*
* @param fNumber|string $divisor The divisor
* @param integer $scale The number of places after the decimal - overrides the scale for this number
* @return fNumber The quotient
*/
public function div($divisor, $scale=NULL)
{
$scale = $this->fixScale($scale);
$divisor = self::parse($divisor, 'number');
if (self::isZero($divisor)) {
throw new fValidationException(
'The divisor specified, %s, is zero, which is an invalid divisor',
$divisor