JAL-98 bespoke fast percentage formatter for consensus tooltip
authorgmungoc <g.m.carstairs@dundee.ac.uk>
Mon, 3 Oct 2016 10:07:12 +0000 (11:07 +0100)
committergmungoc <g.m.carstairs@dundee.ac.uk>
Mon, 3 Oct 2016 10:07:12 +0000 (11:07 +0100)
src/jalview/util/Format.java
test/jalview/util/FormatTest.java [new file with mode: 0644]

index d14e4ad..7121985 100755 (executable)
@@ -947,4 +947,29 @@ public class Format
   {
     return formatString;
   }
+
+  /**
+   * Bespoke method to format percentage float value to the specified number of
+   * decimal places. Avoids use of general-purpose format parsers as a
+   * processing hotspot.
+   * 
+   * @param sb
+   * @param value
+   * @param dp
+   */
+  public static void appendPercentage(StringBuilder sb, float value, int dp)
+  {
+    sb.append((int) value);
+    if (dp > 0)
+    {
+      sb.append(".");
+      while (dp > 0)
+      {
+        value = value - (int) value;
+        value *= 10;
+        sb.append((int) value);
+        dp--;
+      }
+    }
+  }
 }
diff --git a/test/jalview/util/FormatTest.java b/test/jalview/util/FormatTest.java
new file mode 100644 (file)
index 0000000..18199f9
--- /dev/null
@@ -0,0 +1,32 @@
+package jalview.util;
+
+import static org.testng.Assert.assertEquals;
+
+import org.testng.annotations.Test;
+
+public class FormatTest
+{
+  @Test(groups = "Functional")
+  public void testAppendPercentage()
+  {
+    StringBuilder sb = new StringBuilder();
+    Format.appendPercentage(sb, 123.456f, 0);
+    assertEquals(sb.toString(), "123");
+
+    sb.setLength(0);
+    Format.appendPercentage(sb, 123.456f, 1);
+    assertEquals(sb.toString(), "123.4");
+
+    sb.setLength(0);
+    Format.appendPercentage(sb, 123.456f, 2);
+    assertEquals(sb.toString(), "123.45");
+
+    sb.setLength(0);
+    Format.appendPercentage(sb, 123.456f, 3);
+    assertEquals(sb.toString(), "123.456");
+
+    sb.setLength(0);
+    Format.appendPercentage(sb, 123.456f, 4);
+    assertEquals(sb.toString(), "123.4560");
+  }
+}