Skip to content

Commit a5dd1a4

Browse files
authored
Create convinient cast class for numbers with 2 decimal positions
1 parent fbc4137 commit a5dd1a4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/Cast/Decimal2.php

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
namespace Decimal/Cast;
3+
4+
use Decimal\Decimal;
5+
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6+
use Illuminate\Database\Eloquent\Model;
7+
8+
class Decimal2 implements CastsAttributes
9+
{
10+
/**
11+
* Cast the given value.
12+
*
13+
* @param Model $model
14+
* @param string $key
15+
* @param numeric-string|int $value
16+
* @param array $attributes
17+
*/
18+
public function get($model, string $key, $value, array $attributes): Decimal
19+
{
20+
return new Decimal($value, 2);
21+
}
22+
23+
/**
24+
* Prepare the given value for storage.
25+
*
26+
* @param Model $model
27+
* @param string $key
28+
* @param Decimal $value
29+
* @param array $attributes
30+
*
31+
* @return numeric-string
32+
*/
33+
public function set($model, string $key, $value, array $attributes): string
34+
{
35+
return $value->toFixed($decimals, $commas = false, PHP_ROUND_HALF_UP);
36+
}
37+
}

0 commit comments

Comments
 (0)