Skip to content

Commit 7948827

Browse files
committed
money issue
1 parent 0c7c946 commit 7948827

File tree

1 file changed

+43
-19
lines changed

1 file changed

+43
-19
lines changed

src/Money.php

Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Closure;
66
use Filament\Forms\Components\TextInput;
77
use Illuminate\Support\Str;
8+
use Illuminate\Support\Stringable;
89

910
class Money extends TextInput
1011
{
@@ -27,13 +28,10 @@ protected function setUp(): void
2728
}',
2829

2930
'x-on:keyup' => 'function() {
30-
var money = $el.value.replace(/\D/g, "");
31-
money = (money / 100).toFixed(2) + "";
32-
money = money.replace(".", ",");
33-
money = money.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
34-
money = money.replace(/(\d)(\d{3}),/g, "$1.$2,");
35-
36-
$el.value = money;
31+
var money = $el.value;
32+
money = money.replace(/\D/g, \'\');
33+
money = (parseFloat(money) / 100).toLocaleString(\'pt-BR\', { minimumFractionDigits: 2 });
34+
$el.value = money === \'NaN\' ? \'0,00\' : money;
3735
}',
3836
])
3937
->dehydrateMask()
@@ -43,20 +41,10 @@ protected function setUp(): void
4341

4442
public function dehydrateMask(bool|Closure $condition = true): static
4543
{
46-
4744
if ($condition) {
48-
$this->dehydrateStateUsing(
49-
fn ($state): ?float => $state ?
50-
floatval(
51-
Str::of($state)
52-
->replace('.', '')
53-
->replace(',', '.')
54-
->toString()
55-
) * 10 :
56-
null
57-
);
45+
$this->dehydrateStateUsing(fn (?string $state): ?float => $this->convertToFloat($state));
5846
} else {
59-
$this->dehydrateStateUsing(null);
47+
$this->dehydrateStateUsing(fn (?string $state): ?string => $this->convertToNumberFormat($state));
6048
}
6149

6250
return $this;
@@ -68,4 +56,40 @@ public function initialValue(null|string|int|float|Closure $value = '0,00'): sta
6856

6957
return $this;
7058
}
59+
60+
private function sanitizeState(?string $state): ?Stringable
61+
{
62+
$state = Str::of($state)
63+
->replace('.', '')
64+
->replace(',', '');
65+
66+
return $state ?? null;
67+
}
68+
69+
private function convertToFloat(Stringable|string|null $state): float
70+
{
71+
$state = $this->sanitizeState($state);
72+
73+
if (! $state) {
74+
return 0;
75+
}
76+
77+
if ($state->length() > 2) {
78+
$state = $state
79+
->substr(0, $state->length() - 2)
80+
->append('.')
81+
->append($state->substr($state->length() - 2, 2));
82+
} else {
83+
$state = $state->prepend('0.');
84+
}
85+
86+
return floatval($state->toString()) ?? 0;
87+
}
88+
89+
private function convertToNumberFormat(string $state): string
90+
{
91+
$state = $this->convertToFloat($state);
92+
93+
return number_format($state, 2, ',', '.') ?? 0;
94+
}
7195
}

0 commit comments

Comments
 (0)