From b58571e52b6825f9870b0f73bf40c57221f40677 Mon Sep 17 00:00:00 2001 From: Bene Date: Thu, 6 Mar 2025 12:36:57 +0100 Subject: [PATCH] Third decimal for Frequency --- lib/utils/frequency_input_formatter.dart | 52 ++++++++++++++++++------ 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/lib/utils/frequency_input_formatter.dart b/lib/utils/frequency_input_formatter.dart index eec9a94..aa61fb0 100644 --- a/lib/utils/frequency_input_formatter.dart +++ b/lib/utils/frequency_input_formatter.dart @@ -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 parts = filteredText.split('.'); + String whole = parts[0]; + String fraction = parts[1]; - if (formatted.endsWith('.') && digitsOnly.length <= 3) { - formatted = formatted.substring(0, formatted.length - 1); + // Limit to three decimal places + if (fraction.length > 3) { + fraction = fraction.substring(0, 3); + } + + // 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), ); } }