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';
class FrequencyInputFormatter extends TextInputFormatter {
static const int maxDigits = 5;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
String digitsOnly = newValue.text.replaceAll(RegExp(r'[^0-9]'), '');
TextEditingValue oldValue,
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;
}
String formatted = digitsOnly;
if (digitsOnly.length > 3) {
formatted = '${digitsOnly.substring(0, 3)}.${digitsOnly.substring(3)}';
// Format for three decimal places and auto-insert decimal point
if (filteredText.contains('.')) {
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) {
formatted = formatted.substring(0, formatted.length - 1);
// Reconstruct the text
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(
text: formatted,
selection: TextSelection.collapsed(offset: formatted.length),
text: filteredText,
selection: TextSelection.collapsed(offset: filteredText.length),
);
}
}