From 6003347809dbeb2d8af2fa0ef396baa93a201ec1 Mon Sep 17 00:00:00 2001 From: Niki Roo Date: Thu, 11 Apr 2019 07:05:29 +0200 Subject: [PATCH] ..and the reverse operation --- src/be/nikiroo/utils/StringUtils.java | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/be/nikiroo/utils/StringUtils.java b/src/be/nikiroo/utils/StringUtils.java index 9945229..9acf3a1 100644 --- a/src/be/nikiroo/utils/StringUtils.java +++ b/src/be/nikiroo/utils/StringUtils.java @@ -847,6 +847,63 @@ public class StringUtils { return Long.toString(value); } + /** + * The reverse operation to {@link StringUtils#formatNumber(long)}: it will + * read a "display" number that can contain a "M" or "k" suffix and return + * the full value. + *

+ * Of course, the conversion to and from display form is lossy (example: + * 6870 to "6k" to 6000). + * + * @param value + * the value in display form with possible "M" and "k" suffixes, + * can be NULL + * + * @return the value as a number, or 0 if not possible to convert + */ + public static long toNumber(String value) { + return toNumber(value, 0l); + } + + /** + * The reverse operation to {@link StringUtils#formatNumber(long)}: it will + * read a "display" number that can contain a "M" or "k" suffix and return + * the full value. + *

+ * Of course, the conversion to and from display form is lossy (example: + * 6870 to "6k" to 6000). + * + * @param value + * the value in display form with possible "M" and "k" suffixes, + * can be NULL + * @param def + * the default value if it is not possible to convert the given + * value to a number + * + * @return the value as a number, or 0 if not possible to convert + */ + public static long toNumber(String value, long def) { + long count = def; + if (value != null) { + try { + if (value.toLowerCase().endsWith("m")) { + count = Long.parseLong(value.substring(0, + value.length() - 1).trim()); + count *= 1000000; + } else if (value.toLowerCase().endsWith("k")) { + count = Long.parseLong(value.substring(0, + value.length() - 1).trim()); + count *= 1000; + } else { + count = Long.parseLong(value); + } + } catch (NumberFormatException pe) { + } + } + + return count; + } + /** * The "remove accents" pattern. * -- 2.27.0