29 lines
902 B
Dart
29 lines
902 B
Dart
/// Price formatting and parsing for receipt amounts.
|
||
library;
|
||
|
||
/// Matches a price that is the entire line, e.g. `2,09` or `-2.00`.
|
||
final priceOnlyPattern = RegExp(r'^-?\d+[.,]\d{2}$');
|
||
|
||
/// Name (optional) plus a price at the end of the line.
|
||
final trailingPricePattern = RegExp(r'^(.*?)\s+(-?\d+[.,]\d{2})$');
|
||
|
||
/// `2 x 1.50` or `2 X 1,50 3,00` (quantity, unit price, optional line total).
|
||
final quantityPattern = RegExp(
|
||
r'^(\d+)\s*[xX×]\s*(-?\d+[.,]\d{2})(?:\s+(-?\d+[.,]\d{2}))?$',
|
||
);
|
||
|
||
bool isPriceOnly(String line) => priceOnlyPattern.hasMatch(line);
|
||
|
||
double? tryParsePrice(String raw) {
|
||
final cleaned = raw
|
||
.trim()
|
||
.replaceAll('€', '')
|
||
.replaceAll(RegExp(r'\s'), '')
|
||
.replaceAll(',', '.');
|
||
return double.tryParse(cleaned);
|
||
}
|
||
|
||
String formatEuro(double value) => '€ ${value.toStringAsFixed(2)}';
|
||
|
||
double roundMoney(double value) => (value * 100).round() / 100;
|