forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object-to-integer-in-dart.dart
39 lines (35 loc) · 1.04 KB
/
object-to-integer-in-dart.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Want to support my work 🤝? https://buymeacoffee.com/vandad
enum ToIntStrategy { round, floor, ceil }
typedef ToIntOnErrorHandler = int Function(Object e);
extension ToInt on Object {
int toInteger({
ToIntStrategy strategy = ToIntStrategy.round,
ToIntOnErrorHandler? onError,
}) {
try {
final doubleValue = double.parse(toString());
switch (strategy) {
case ToIntStrategy.round:
return doubleValue.round();
case ToIntStrategy.floor:
return doubleValue.floor();
case ToIntStrategy.ceil:
return doubleValue.ceil();
}
} catch (e) {
if (onError != null) {
return onError(e);
} else {
return -1;
}
}
}
}
void testIt() {
assert('xyz'.toInteger(onError: (_) => 100) == 100);
assert(1.5.toInteger() == 2);
assert(1.6.toInteger() == 2);
assert('1.2'.toInteger(strategy: ToIntStrategy.floor) == 1);
assert('1.2'.toInteger(strategy: ToIntStrategy.ceil) == 2);
assert('1.5'.toInteger(strategy: ToIntStrategy.round) == 2);
}