Third decimal for Frequency

This commit is contained in:
2025-03-06 12:36:57 +01:00
parent a857648c48
commit b58571e52b

View File

@@ -1,29 +1,55 @@
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
class FrequencyInputFormatter extends TextInputFormatter { class FrequencyInputFormatter extends TextInputFormatter {
static const int maxDigits = 5;
@override @override
TextEditingValue formatEditUpdate( TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) { TextEditingValue oldValue,
String digitsOnly = newValue.text.replaceAll(RegExp(r'[^0-9]'), ''); TextEditingValue newValue,
) {
// Skip formatting if deleting
if (oldValue.text.length > newValue.text.length) {
return newValue;
}
if (digitsOnly.length > maxDigits) { // Allow only numbers and decimal point
String filteredText = newValue.text.replaceAll(RegExp(r'[^\d.]'), '');
// Only allow one decimal point
if (filteredText.split('.').length > 2) {
return oldValue; return oldValue;
} }
String formatted = digitsOnly; // Format for three decimal places and auto-insert decimal point
if (digitsOnly.length > 3) { if (filteredText.contains('.')) {
formatted = '${digitsOnly.substring(0, 3)}.${digitsOnly.substring(3)}'; List<String> parts = filteredText.split('.');
String whole = parts[0];
String fraction = parts[1];
// Limit to three decimal places
if (fraction.length > 3) {
fraction = fraction.substring(0, 3);
} }
if (formatted.endsWith('.') && digitsOnly.length <= 3) { // Reconstruct the text
formatted = formatted.substring(0, formatted.length - 1); filteredText = "$whole.$fraction";
} else {
// Auto-insert decimal point after the third digit
if (filteredText.length > 3) {
String whole = filteredText.substring(0, 3);
String fraction = filteredText.substring(3);
// Limit fraction to three digits
if (fraction.length > 3) {
fraction = fraction.substring(0, 3);
}
filteredText = "$whole.$fraction";
}
} }
return TextEditingValue( return TextEditingValue(
text: formatted, text: filteredText,
selection: TextSelection.collapsed(offset: formatted.length), selection: TextSelection.collapsed(offset: filteredText.length),
); );
} }
} }