Skip to content

Commit 6b3948e

Browse files
committed
add NumberHelper::numberSub
1 parent 54909bc commit 6b3948e

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

src/Helpers/NumberHelper.php

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,15 +118,28 @@ public static function geoDistance(float $lng1 = 0, float $lat1 = 0, float $lng2
118118

119119

120120
/**
121-
* 数值格式化
122-
* @param float|int $number 要格式化的数字
121+
* 数值格式化(会四舍五入)
122+
* @param float|int|string $number 要格式化的数字
123123
* @param int $decimals 小数位数
124-
* @param string $decPoint 小数点
125-
* @param string $thousandssep 千分位符号
126124
* @return string
127125
*/
128-
public static function numberFormat($number, int $decimals = 2, string $decPoint = '.', string $thousandssep = ''): string {
129-
return number_format($number, $decimals, $decPoint, $thousandssep);
126+
public static function numberFormat($number, int $decimals = 2): string {
127+
return number_format(floatval($number), $decimals, '.', '');
128+
}
129+
130+
131+
/**
132+
* 数值截取(不会四舍五入)
133+
* @param float|int|string $number 要格式化的数字
134+
* @param int $decimals 小数位数
135+
* @return float
136+
*/
137+
public static function numberSub($number, int $decimals = 2): float {
138+
if ($decimals == 0 && ValidateHelper::isInteger($number)) {
139+
return floatval($number);
140+
}
141+
142+
return intval(floatval($number) * pow(10, $decimals)) / pow(10, $decimals);
130143
}
131144

132145

tests/Unit/NumberHelperTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,18 @@ public function testNumberFormat() {
9494
}
9595

9696

97+
public function testNumberSub() {
98+
$num1 = '123000';
99+
$num2 = 1234.56789;
100+
101+
$res1 = NumberHelper::numberSub($num1, 0);
102+
$res2 = NumberHelper::numberSub($num2, 3);
103+
104+
$this->assertEquals('123000', $res1);
105+
$this->assertEquals('1234.567', $res2);
106+
}
107+
108+
97109
public function testRandFloat() {
98110
$tests = [
99111
[0, 1],

0 commit comments

Comments
 (0)