-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathcurrency_formatter.dart
74 lines (61 loc) · 2.09 KB
/
currency_formatter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
class CurrencyFormatter extends TextInputFormatter {
CurrencyFormatter({
this.locale,
this.name,
this.symbol,
this.isGrouped = false,
});
final String? locale;
final String? name;
final String? symbol;
final bool isGrouped;
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final isInserted = oldValue.text.length + 1 == newValue.text.length && newValue.text.startsWith(oldValue.text);
final isRemoved = oldValue.text.length - 1 == newValue.text.length && oldValue.text.startsWith(newValue.text);
if (!isInserted && !isRemoved) {
return oldValue;
}
final format = NumberFormat.currency(
locale: locale,
name: name,
symbol: symbol,
);
if (isGrouped) {
format.turnOffGrouping();
}
final isNegativeValue = newValue.text.startsWith('-');
var newText = newValue.text.replaceAll(RegExp('[^0-9]'), '');
if (isRemoved && !_lastCharacterIsDigit(oldValue.text)) {
final length = newText.length - 1;
newText = newText.substring(0, length > 0 ? length : 0);
}
if (newText.trim() == '') {
return newValue.copyWith(
text: isNegativeValue ? '-' : '',
selection: TextSelection.collapsed(offset: isNegativeValue ? 1 : 0),
);
} else if (newText == '00' || newText == '000') {
return TextEditingValue(
text: isNegativeValue ? '-' : '',
selection: TextSelection.collapsed(offset: isNegativeValue ? 1 : 0),
);
}
num newInt = int.parse(newText);
if (format.decimalDigits! > 0) {
newInt /= pow(10, format.decimalDigits!);
}
final newString = (isNegativeValue ? '-' : '') + format.format(newInt).trim();
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(offset: newString.length),
);
}
static bool _lastCharacterIsDigit(String text) {
final lastChar = text.substring(text.length - 1);
return RegExp('[0-9]').hasMatch(lastChar);
}
}