Files
FlClash/lib/common/num.dart
T

68 lines
1.8 KiB
Dart
Raw Normal View History

2025-07-31 17:09:18 +08:00
import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/models/common.dart';
2024-12-09 01:40:39 +08:00
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart' show NumberFormat;
import 'package:material_ui/material_ui.dart';
2024-12-09 01:40:39 +08:00
/// Pinned to English so every locale reads K and M, never 万 or тыс.
final _compactFormat = NumberFormat.compact(locale: 'en');
2024-12-09 01:40:39 +08:00
extension NumExt on num {
String get compact => _compactFormat.format(this);
2025-06-07 01:48:34 +08:00
String fixed({int decimals = 2}) {
2025-02-09 18:39:38 +08:00
String formatted = toStringAsFixed(decimals);
if (formatted.contains('.')) {
formatted = formatted.replaceAll(RegExp(r'0*$'), '');
if (formatted.endsWith('.')) {
formatted = formatted.substring(0, formatted.length - 1);
}
}
return formatted;
2024-04-30 23:38:49 +08:00
}
2025-07-31 17:09:18 +08:00
TrafficShow get traffic {
2026-02-02 10:14:13 +08:00
const units = TrafficUnit.values;
2025-07-31 17:09:18 +08:00
var size = toDouble();
var unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return TrafficShow(
value: size.fixed(decimals: 1),
unit: units[unitIndex].name,
);
}
2025-10-14 15:13:52 +08:00
TrafficShow get shortTraffic {
2026-02-02 10:14:13 +08:00
const units = TrafficUnit.values;
2025-10-14 15:13:52 +08:00
var size = toDouble();
var unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return TrafficShow(
value: size.toStringAsFixed(0),
unit: ' ${units[unitIndex].name}',
);
}
2024-04-30 23:38:49 +08:00
}
2024-12-09 01:40:39 +08:00
extension DoubleExt on double {
2025-06-07 01:48:34 +08:00
bool moreOrEqual(double value) {
return this > value || (value - this).abs() < precisionErrorTolerance;
2024-12-09 01:40:39 +08:00
}
}
extension OffsetExt on Offset {
double getCrossAxisOffset(Axis direction) {
return direction == Axis.vertical ? dx : dy;
}
double getMainAxisOffset(Axis direction) {
return direction == Axis.vertical ? dy : dx;
}
}