Skip to content

Commit 1c2ac49

Browse files
committed
Implement BigDecimal::getPrecision()
Fixes #58
1 parent 901eddb commit 1c2ac49

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## UNRELEASED (0.12.3)
6+
7+
**New features**
8+
9+
- `BigDecimal::getPrecision()` Returns the number of significant digits in a decimal number
10+
511
## [0.12.2](https://github.com/brick/math/releases/tag/0.12.2) - 2025-02-26
612

713
⚡️ **Performance improvements**

src/BigDecimal.php

+27
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,33 @@ public function getScale() : int
571571
return $this->scale;
572572
}
573573

574+
/**
575+
* Returns the number of significant digits in the number.
576+
*
577+
* This is the number of digits to both sides of the decimal point, stripped of leading zeros.
578+
* The sign has no impact on the result.
579+
*
580+
* Examples:
581+
* 0 => 0
582+
* 0.0 => 0
583+
* 123 => 3
584+
* 123.456 => 6
585+
* 0.00123 => 3
586+
* 0.0012300 => 5
587+
*/
588+
public function getPrecision(): int
589+
{
590+
$value = $this->value;
591+
592+
if ($value === '0') {
593+
return 0;
594+
}
595+
596+
$length = \strlen($value);
597+
598+
return ($value[0] === '-') ? $length - 1 : $length;
599+
}
600+
574601
/**
575602
* Returns a string representing the integral part of this decimal number.
576603
*

tests/BigDecimalTest.php

+33
Original file line numberDiff line numberDiff line change
@@ -2247,6 +2247,39 @@ public static function providerSign() : array
22472247
];
22482248
}
22492249

2250+
#[DataProvider('providerGetPrecision')]
2251+
public function testGetPrecision(string $number, int $precision) : void
2252+
{
2253+
self::assertSame($precision, BigDecimal::of($number)->getPrecision());
2254+
self::assertSame($precision, BigDecimal::of($number)->negated()->getPrecision());
2255+
}
2256+
2257+
public static function providerGetPrecision() : array
2258+
{
2259+
return [
2260+
['0', 0],
2261+
['0.0', 0],
2262+
['0.00', 0],
2263+
['1', 1],
2264+
['12', 2],
2265+
['123', 3],
2266+
['1.2', 2],
2267+
['1.23', 3],
2268+
['1.230', 4],
2269+
['123.456', 6],
2270+
['0.123', 3],
2271+
['0.1230', 4],
2272+
['0.0123', 3],
2273+
['0.01230', 4],
2274+
['0.00123', 3],
2275+
['0.001230', 4],
2276+
['0.0012300', 5],
2277+
['1234567890.12345678901234567890123456789012345678901234567890', 60],
2278+
['0.0000000000000000000000000000000000000000000000000000000000012345', 5],
2279+
['0.00000000000000000000000000000000000000000000000000000000000123450', 6],
2280+
];
2281+
}
2282+
22502283
/**
22512284
* @param string $number The number to test.
22522285
* @param string $expected The expected integral value.

0 commit comments

Comments
 (0)