toFormatAmount method
Implementation
TextEditingValue toFormatAmount() {
try {
final text = this.text.trim();
// Logging (اختياري)
// JLog.d_('----------- [BEFORE] -----------');
// JLog.d_('string: $text');
// JLog.d_('length: ${text.length}');
// JLog.d_('selection: ${this.selection}');
if (text.isEmpty) {
return const TextEditingValue(
text: '',
selection: TextSelection.collapsed(offset: 0),
);
}
if (text == '.') {
return const TextEditingValue(
text: '0.',
selection: TextSelection.collapsed(offset: 2),
);
}
final last = text.characters.last;
String integerText = '';
String decimalText = '';
bool point = false;
for (var c in text.characters) {
if (last != '#' && c == '#') {
return const TextEditingValue(
text: '',
selection: TextSelection.collapsed(offset: 0),
);
}
if (RegExp(r'\d').hasMatch(c)) {
if (point) {
decimalText += c;
if (decimalText.length >= 2) break;
} else {
integerText += c;
}
} else if (c == '.') {
point = true;
}
}
if (integerText.isEmpty && point) {
integerText = '0';
}
final numberDouble = double.tryParse(integerText) ?? 0.0;
var format = JFormatter.currency.format(numberDouble);
var vs = format.length - text.length;
if (point) {
format += '.$decimalText';
vs += 1 + decimalText.length;
}
return TextEditingValue(
text: format,
selection: TextSelection.collapsed(offset: selection.end + vs),
);
} catch (ex) {
// JLog.ex(ex);
return this;
}
}