dev
dart 47 lines 1.38 KB
Raw
1 import "package:cw_core/amount/money.dart";
2 import "package:intl/intl.dart";
3
4 extension WithLocalSeparator on Money {
5 String toLocalStringWithSymbol({
6 int? fractionalDigits,
7 bool trimZeros = true,
8 bool useBaseUnit = false,
9 bool withSymbolPrefix = false,
10 String? locale,
11 }) {
12 final amount = toLocalStringWithPrecision(
13 fractionalDigits: fractionalDigits,
14 trimZeros: trimZeros,
15 useBaseUnit: useBaseUnit,
16 locale: locale,
17 );
18 final symbol = getSymbol(useBaseUnit: useBaseUnit);
19
20 return withSymbolPrefix ? "$symbol $amount" : "$amount $symbol";
21 }
22
23 String toLocalStringWithPrecision({
24 int? fractionalDigits,
25 bool trimZeros = true,
26 bool useBaseUnit = false,
27 String? locale,
28 }) =>
29 _withLocalSeparator(
30 toStringWithPrecision(
31 fractionalDigits: fractionalDigits,
32 trimZeros: trimZeros,
33 useBaseUnit: useBaseUnit,
34 ),
35 locale: locale,
36 );
37
38 String _withLocalSeparator(String amount, {String? locale}) {
39 final isNegative = amount.startsWith("-");
40 final formater = NumberFormat("#,###", locale);
41 final parts = (isNegative ? amount.substring(1) : amount).split(".");
42 final formatted = [formater.format(int.tryParse(parts.first) ?? 0), ...parts.sublist(1)]
43 .join(formater.symbols.DECIMAL_SEP);
44
45 return isNegative ? "-$formatted" : formatted;
46 }
47 }