Add filter for concise numbers (three most significant digits only).
[demoscenemusic.git] / src / main / java / net / pterodactylus / demoscenemusic / template / ConciseNumberFilter.java
diff --git a/src/main/java/net/pterodactylus/demoscenemusic/template/ConciseNumberFilter.java b/src/main/java/net/pterodactylus/demoscenemusic/template/ConciseNumberFilter.java
new file mode 100644 (file)
index 0000000..9ea4b8c
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * DemosceneMusic - ConciseNumberFilter.java - Copyright © 2012 David Roden
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.pterodactylus.demoscenemusic.template;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import net.pterodactylus.util.number.Numbers;
+import net.pterodactylus.util.template.Filter;
+import net.pterodactylus.util.template.TemplateContext;
+
+/**
+ * {@link Filter} implementation that only shows the three most significant
+ * digits of a number, adding prefix for kilo (kibi, actually), mega (mebi), et
+ * cetera, as necessary.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class ConciseNumberFilter implements Filter {
+
+       private static final List<String> prefixes = Arrays.asList("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei");
+
+       /**
+        * {@inheritDoc}
+        */
+       @Override
+       public Object format(TemplateContext templateContext, Object data, Map<String, Object> parameters) {
+               double number = Numbers.safeParseLong(data, 0L);
+               int prefix = 0;
+               while (number > 1023) {
+                       prefix++;
+                       number /= 1024.0;
+               }
+               if (number >= 1000) {
+                       return String.format("%1.2f %s", number / 1024.0, prefixes.get(prefix + 1));
+               }
+               if (number >= 100) {
+                       return String.format("%1.0f %s", number, prefixes.get(prefix));
+               }
+               if (number >= 10) {
+                       return String.format("%1.1f %s", number, prefixes.get(prefix));
+               }
+               return String.format("%1.2f %s", number, prefixes.get(prefix));
+       }
+
+}