From 57cded1c79ae32187bd0ffd802f9d6f6c5bc3450 Mon Sep 17 00:00:00 2001 From: Sambo Chea Date: Mon, 7 Jun 2021 17:50:04 +0700 Subject: [PATCH] Task: Add format number with precision and updated for dart shared --- example/cubetiq_functions.dart | 7 +++++++ lib/src/text/extension.dart | 4 ++++ lib/src/text/functions.dart | 7 +++++++ 3 files changed, 18 insertions(+) create mode 100644 example/cubetiq_functions.dart diff --git a/example/cubetiq_functions.dart b/example/cubetiq_functions.dart new file mode 100644 index 0000000..e73f13b --- /dev/null +++ b/example/cubetiq_functions.dart @@ -0,0 +1,7 @@ +import 'package:cubetiq/src/text/functions.dart'; +import 'package:cubetiq/src/xlog/xlog.dart'; + +void main(List args) { + XLog.debug(StringUtils.format(10.5555, 2)); + XLog.debug(StringUtils.formatFromString('10.5555', 2)); +} \ No newline at end of file diff --git a/lib/src/text/extension.dart b/lib/src/text/extension.dart index b838c6a..c1d011a 100644 --- a/lib/src/text/extension.dart +++ b/lib/src/text/extension.dart @@ -32,4 +32,8 @@ extension StringExtensionOnNullable on String? { bool get isNullOrEmptyOrBlank => StringUtils.isNullOrEmptyOrBlank(this); bool get isEqualsIgnoreCase => StringUtils.equalsIgnoreCase(this, this); + + String toPrecision([int precision = 2]) { + return StringUtils.formatFromString(this, precision); + } } diff --git a/lib/src/text/functions.dart b/lib/src/text/functions.dart index 0ff2f36..a35e252 100644 --- a/lib/src/text/functions.dart +++ b/lib/src/text/functions.dart @@ -6,6 +6,13 @@ class StringUtils { return n.toStringAsFixed(n.truncateToDouble() == n ? precision : precision); } + /// Format number from String with precision + static String formatFromString(String? text, [int precision = 2]) { + text ??= '0.0'; + var n = double.parse(text); + return n.toStringAsFixed(n.truncateToDouble() == n ? precision : precision); + } + /// Text format with custom args static String? textFormat(String? text, List args) => TextFormatter(text).format(args);