Passed
Push — FixRounding ( 5ebe98 )
by Daniel
02:51
created

DecimalMath::bumpDigitsForRounding()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 2
eloc 8
nc 2
nop 3
1
<?php
2
3
namespace DataValues;
4
5
use InvalidArgumentException;
6
7
/**
8
 * Class for performing basic arithmetic and other transformations
9
 * on DecimalValues.
10
 *
11
 * This uses the bcmath library if available. Otherwise, it falls back on
12
 * using floating point operations.
13
 *
14
 * @note: this is not a genuine decimal arithmetics implementation,
15
 * and should not be used for financial computations, physical simulations, etc.
16
 *
17
 * @see DecimalValue
18
 *
19
 * @since 0.1
20
 *
21
 * @license GPL-2.0+
22
 * @author Daniel Kinzler
23
 */
24
class DecimalMath {
25
26
	/**
27
	 * Whether to use the bcmath library.
28
	 *
29
	 * @var bool
30
	 */
31
	private $useBC;
32
33
	/**
34
	 * @param bool|null $useBC Whether to use the bcmath library. If null,
35
	 *        bcmath will automatically be used if available.
36
	 */
37
	public function __construct( $useBC = null ) {
38
		if ( $useBC === null ) {
39
			$useBC = function_exists( 'bcscale' );
40
		}
41
42
		$this->useBC = $useBC;
43
	}
44
45
	/**
46
	 * @param int|float|string $number
47
	 *
48
	 * @return DecimalValue
49
	 */
50
	private function makeDecimalValue( $number ) {
51
52
		if ( is_string( $number ) && $number !== '' ) {
53
			if ( $number[0] !== '-' && $number[0] !== '+' ) {
54
				$number = '+' . $number;
55
			}
56
		}
57
58
		return new DecimalValue( $number );
59
	}
60
61
	/**
62
	 * Whether this is using the bcmath library.
63
	 *
64
	 * @return bool
65
	 */
66
	public function getUseBC() {
67
		return $this->useBC;
68
	}
69
70
	/**
71
	 * Returns the product of the two values.
72
	 *
73
	 * @param DecimalValue $a
74
	 * @param DecimalValue $b
75
	 *
76
	 * @return DecimalValue
77
	 */
78
	public function product( DecimalValue $a, DecimalValue $b ) {
79
		if ( $this->useBC ) {
80
			$scale = strlen( $a->getFractionalPart() ) + strlen( $b->getFractionalPart() );
81
			$product = bcmul( $a->getValue(), $b->getValue(), $scale );
82
		} else {
83
			$product = $a->getValueFloat() * $b->getValueFloat();
84
		}
85
86
		return $this->makeDecimalValue( $product );
87
	}
88
89
	/**
90
	 * Returns the sum of the two values.
91
	 *
92
	 * @param DecimalValue $a
93
	 * @param DecimalValue $b
94
	 *
95
	 * @return DecimalValue
96
	 */
97
	public function sum( DecimalValue $a, DecimalValue $b ) {
98
		if ( $this->useBC ) {
99
			$scale = max( strlen( $a->getFractionalPart() ), strlen( $b->getFractionalPart() ) );
100
			$sum = bcadd( $a->getValue(), $b->getValue(), $scale );
101
		} else {
102
			$sum = $a->getValueFloat() + $b->getValueFloat();
103
		}
104
105
		return $this->makeDecimalValue( $sum );
106
	}
107
108
	/**
109
	 * Returns the minimum of the two values
110
	 *
111
	 * @param DecimalValue $a
112
	 * @param DecimalValue $b
113
	 *
114
	 * @return DecimalValue
115
	 */
116
	public function min( DecimalValue $a, DecimalValue $b ) {
117
118
		if ( $this->useBC ) {
119
			$scale = max( strlen( $a->getFractionalPart() ), strlen( $b->getFractionalPart() ) );
120
			$comp = bccomp( $a->getValue(), $b->getValue(), $scale );
121
			$min = $comp > 0 ? $b : $a;
122
		} else {
123
			$min = min( $a->getValueFloat(), $b->getValueFloat() );
124
			$min = $this->makeDecimalValue( $min );
125
		}
126
127
		return $min;
128
	}
129
130
	/**
131
	 * Returns the maximum of the two values
132
	 *
133
	 * @param DecimalValue $a
134
	 * @param DecimalValue $b
135
	 *
136
	 * @return DecimalValue
137
	 */
138
	public function max( DecimalValue $a, DecimalValue $b ) {
139
140
		if ( $this->useBC ) {
141
			$scale = max( strlen( $a->getFractionalPart() ), strlen( $b->getFractionalPart() ) );
142
			$comp = bccomp( $a->getValue(), $b->getValue(), $scale );
143
			$max = $comp > 0 ? $a : $b;
144
		} else {
145
			$max = max( $a->getValueFloat(), $b->getValueFloat() );
146
			$max = $this->makeDecimalValue( $max );
147
		}
148
149
		return $max;
150
	}
151
152
	/**
153
	 * Returns the given value, with any insignificant digits removed or zeroed.
154
	 *
155
	 * Rounding is applied  using the "round half away from zero" rule (that is, +0.5 is
156
	 * rounded to +1 and -0.5 is rounded to -1).
157
	 *
158
	 * @since 0.1
159
	 *
160
	 * @param DecimalValue $decimal
161
	 * @param int $significantDigits The number of digits to retain, counting the decimal point,
162
	 *        but not counting the leading sign.
163
	 *
164
	 * @throws InvalidArgumentException
165
	 * @return DecimalValue
166
	 */
167
	public function roundToDigit( DecimalValue $decimal, $significantDigits ) {
168
		$value = $decimal->getValue();
169
		$rounded = $this->roundDigits( $value, $significantDigits );
170
		return new DecimalValue( $rounded );
171
	}
172
173
	/**
174
	 * Returns the given value, with any insignificant digits removed or zeroed.
175
	 *
176
	 * Rounding is applied  using the "round half away from zero" rule (that is, +0.5 is
177
	 * rounded to +1 and -0.5 is rounded to -1).
178
	 *
179
	 * @since 0.1
180
	 *
181
	 * @param DecimalValue $decimal
182
	 * @param int $significantExponent 	 The exponent of the last significant digit,
183
	 *        e.g. -1 for "keep the first digit after the decimal point", or 2 for
184
	 *        "zero the last two digits before the decimal point".
185
	 *
186
	 * @throws InvalidArgumentException
187
	 * @return DecimalValue
188
	 */
189
	public function roundToExponent( DecimalValue $decimal, $significantExponent ) {
190
		//NOTE: the number of digits to keep (without the leading sign)
191
		//      is the same as the exponent's offset (with the leaqding sign).
192
		$digits = $this->getPositionForExponent( $significantExponent, $decimal );
193
		return $this->roundToDigit( $decimal, $digits );
194
	}
195
196
	/**
197
	 * Returns the (zero based) position for the given exponent in
198
	 * the given decimal string, counting the decimal point and the leading sign.
199
	 *
200
	 * @example: the position of exponent 0 in "+10.03" is 2.
201
	 * @example: the position of exponent 1 in "+210.03" is 2.
202
	 * @example: the position of exponent -2 in "+1.037" is 4.
203
	 *
204
	 * @param int $exponent
205
	 * @param DecimalValue $decimal
206
	 *
207
	 * @return int
208
	 */
209
	public function getPositionForExponent( $exponent, DecimalValue $decimal ) {
210
		$decimal = $decimal->getValue();
211
212
		$pointPos = strpos( $decimal, '.' );
213
		if ( $pointPos === false ) {
214
			$pointPos = strlen( $decimal );
215
		}
216
217
		// account for leading sign
218
		$pointPos--;
219
220
		if ( $exponent < 0 ) {
221
			// account for decimal point
222
			$position = $pointPos +1 - $exponent;
223
		} else {
224
			// make sure we don't remove more digits than are there
225
			$position = max( 0, $pointPos - $exponent );
226
		}
227
228
		return $position;
229
	}
230
231
	/**
232
	 * Returns the given value, with any insignificant digits removed or zeroed.
233
	 *
234
	 * Rounding is applied using the "round half away from zero" rule (that is, +0.5 is
235
	 * rounded to +1 and -0.5 is rounded to -1).
236
	 *
237
	 * @see round()
238
	 *
239
	 * @param string $value
240
	 * @param int $significantDigits
241
	 *
242
	 * @throws InvalidArgumentException if $significantDigits is smaller than 0
243
	 * @return string
244
	 */
245
	private function roundDigits( $value, $significantDigits ) {
246
		if ( !is_int( $significantDigits ) ) {
247
			throw new InvalidArgumentException( '$significantDigits must be an integer' );
248
		}
249
250
		// keeping no digits results in zero.
251
		if ( $significantDigits === 0 ) {
252
			return '+0';
253
		}
254
255
		$len = strlen( $value );
256
257
		// keeping all digits means no rounding
258
		if ( $significantDigits >= ( $len -1 ) ) {
259
			return $value;
260
		}
261
262
		if ( $significantDigits < 0 ) {
263
			throw new InvalidArgumentException( '$significantDigits must be larger than zero.' );
264
		}
265
266
		// whether the last character is already part of the integer part of the decimal value
267
		$i = min( $significantDigits +1, $len ); // account for the sign
268
		$ch = $i < $len ? $value[$i] : '0';
269
270
		if ( $ch === '.' ) {
271
			// NOTE: we expect the input to be well formed, so it cannot end with a '.'
272
			$i++;
273
			$ch = $i < $len ? $value[$i] : '0';
274
		}
275
276
		// split in significant and insignificant part
277
		$rounded = substr( $value, 0, $i );
278
279
		if ( strpos( $rounded, '.' ) === false ) {
280
			$suffix = substr( $value, $i );
281
282
			// strip insignificant digits after the decimal point
283
			$ppos = strpos( $suffix, '.' );
284
			if ( $ppos !== false ) {
285
				$suffix = substr( $suffix, 0, $ppos );
286
			}
287
288
			// zero out insignificant digits
289
			$suffix = strtr( $suffix, '123456789', '000000000' );
290
		} else {
291
			// decimal point is in $rounded, so $suffix is insignificant
292
			$suffix = '';
293
		}
294
295
		if ( ord( $ch ) >= ord( '5' ) ) {
296
			$rounded = $this->bumpDigits( $rounded );
297
		}
298
299
		$rounded .= $suffix;
300
301
		if ( $significantDigits > strlen( $rounded ) -1 ) {
302
			if ( strpos( $rounded, '.' ) !== false ) {
303
				$rounded = str_pad( $rounded, $significantDigits+1, '0', STR_PAD_RIGHT );
304
			}
305
		}
306
307
		// strip trailing decimal point
308
		$rounded = rtrim( $rounded, '.' );
309
310
		return $rounded;
311
	}
312
313
	/**
314
	 * Increment the least significant digit by one if it is less than 9, and
315
	 * set it to zero and continue to the next more significant digit if it is 9.
316
	 * Exception: bump( 0 ) == 1;
317
	 *
318
	 * E.g.: bump( 0.2 ) == 0.3, bump( -0.09 ) == -0.10, bump( 9.99 ) == 10.00
319
	 *
320
	 * This is the inverse of @see slump()
321
	 *
322
	 * @since 0.1
323
	 *
324
	 * @param DecimalValue $decimal
325
	 *
326
	 * @return DecimalValue
327
	 */
328
	public function bump( DecimalValue $decimal ) {
329
		$value = $decimal->getValue();
330
		$bumped = $this->bumpDigits( $value );
331
		return new DecimalValue( $bumped );
332
	}
333
334
	/**
335
	 * Increment the least significant digit by one if it is less than 9, and
336
	 * set it to zero and continue to the next more significant digit if it is 9.
337
	 *
338
	 * @see bump()
339
	 *
340
	 * @param string $value
341
	 * @return string
342
	 */
343
	private function bumpDigits( $value ) {
344
		if ( $value === '+0' ) {
345
			return '+1';
346
		}
347
348
		$bumped = '';
349
350
		for ( $i = strlen( $value ) -1; $i >= 0; $i-- ) {
351
			$ch = $value[$i];
352
353
			if ( $ch === '.' ) {
354
				$bumped = '.' . $bumped;
355
				continue;
356
			} elseif ( $ch === '9' ) {
357
				$bumped = '0' . $bumped;
358
				continue;
359
			} elseif ( $ch === '+' || $ch === '-' ) {
360
				$bumped = $ch . '1' . $bumped;
361
				break;
362
			} else {
363
				$bumped =  chr( ord( $ch ) + 1 ) . $bumped;
364
				break;
365
			}
366
		}
367
368
		$bumped = substr( $value, 0, $i ) . $bumped;
369
		return $bumped;
370
	}
371
372
	/**
373
	 * Decrement the least significant digit by one if it is more than 0, and
374
	 * set it to 9 and continue to the next more significant digit if it is 0.
375
	 * Exception: slump( 0 ) == -1;
376
	 *
377
	 * E.g.: slump( 0.2 ) == 0.1, slump( -0.10 ) == -0.01, slump( 0.0 ) == -1.0
378
	 *
379
	 * This is the inverse of @see bump()
380
	 *
381
	 * @since 0.1
382
	 *
383
	 * @param DecimalValue $decimal
384
	 *
385
	 * @return DecimalValue
386
	 */
387
	public function slump( DecimalValue $decimal ) {
388
		$value = $decimal->getValue();
389
		$slumped = $this->slumpDigits( $value );
390
		return new DecimalValue( $slumped );
391
	}
392
393
	/**
394
	 * Decrement the least significant digit by one if it is more than 0, and
395
	 * set it to 9 and continue to the next more significant digit if it is 0.
396
	 *
397
	 * @see slump()
398
	 *
399
	 * @param string $value
400
	 * @return string
401
	 */
402
	private function slumpDigits( $value ) {
403
		if ( $value === '+0' ) {
404
			return '-1';
405
		}
406
407
		// a "precise zero" will become negative
408
		if ( preg_match( '/^\+0\.(0*)0$/', $value, $m ) ) {
409
			return '-0.' . $m[1] . '1';
410
		}
411
412
		$slumped = '';
413
414
		for ( $i = strlen( $value ) -1; $i >= 0; $i-- ) {
415
			$ch = substr( $value, $i, 1 );
416
417
			if ( $ch === '.' ) {
418
				$slumped = '.' . $slumped;
419
				continue;
420
			} elseif ( $ch === '0' ) {
421
				$slumped = '9' . $slumped;
422
				continue;
423
			} elseif ( $ch === '+' || $ch === '-' ) {
424
				$slumped = '0';
425
				break;
426
			} else {
427
				$slumped =  chr( ord( $ch ) - 1 ) . $slumped;
428
				break;
429
			}
430
		}
431
432
		// preserve prefix
433
		$slumped = substr( $value, 0, $i ) . $slumped;
434
435
		$slumped = $this->stripLeadingZeros( $slumped );
436
437
		if ( $slumped === '-0' ) {
438
			$slumped = '+0';
439
		}
440
441
		return $slumped;
442
	}
443
444
	/**
445
	 * @param string $digits
446
	 *
447
	 * @return string
448
	 */
449
	private function stripLeadingZeros( $digits ) {
450
		$digits = preg_replace( '/^([-+])0+(?=\d)/', '\1', $digits );
451
		return $digits;
452
	}
453
454
	/**
455
	 * Shift the decimal point according to the given exponent.
456
	 *
457
	 * @param DecimalValue $decimal
458
	 * @param int $exponent The exponent to apply (digits to shift by). A Positive exponent
459
	 * shifts the decimal point to the right, a negative exponent shifts to the left.
460
	 *
461
	 * @throws InvalidArgumentException
462
	 * @return DecimalValue
463
	 */
464
	public function shift( DecimalValue $decimal, $exponent ) {
465
		if ( !is_int( $exponent ) ) {
466
			throw new InvalidArgumentException( '$exponent must be an integer' );
467
		}
468
469
		if ( $exponent == 0 ) {
470
			return $decimal;
471
		}
472
473
		$sign = $decimal->getSign();
474
		$intPart = $decimal->getIntegerPart();
475
		$fractPart = $decimal->getFractionalPart();
476
477
		if ( $exponent < 0 ) {
478
			$intPart = $this->shiftLeft( $intPart, $exponent );
479
		} else {
480
			$fractPart = $this->shiftRight( $fractPart, $exponent );
481
		}
482
483
		$digits = $sign . $intPart . $fractPart;
484
		$digits = $this->stripLeadingZeros( $digits );
485
486
		return new DecimalValue( $digits );
487
	}
488
489
	/**
490
	 * @param string $intPart
491
	 * @param int $exponent must be negative
492
	 *
493
	 * @return string
494
	 */
495
	private function shiftLeft( $intPart, $exponent ) {
496
		//note: $exponent is negative!
497
		if ( -$exponent < strlen( $intPart ) ) {
498
			$intPart = substr( $intPart, 0, $exponent ) . '.' . substr( $intPart, $exponent );
499
		} else {
500
			$intPart = '0.' . str_pad( $intPart, -$exponent, '0', STR_PAD_LEFT );
501
		}
502
503
		return $intPart;
504
	}
505
506
	/**
507
	 * @param string $fractPart
508
	 * @param int $exponent must be positive
509
	 *
510
	 * @return string
511
	 */
512
	private function shiftRight( $fractPart, $exponent ) {
513
		//note: $exponent is positive.
514
		if ( $exponent < strlen( $fractPart ) ) {
515
			$fractPart = substr( $fractPart, 0, $exponent ) . '.' . substr( $fractPart, $exponent );
516
		} else {
517
			$fractPart = str_pad( $fractPart, $exponent, '0', STR_PAD_RIGHT );
518
		}
519
520
		return $fractPart;
521
	}
522
523
}
524