From: gmungoc Date: Mon, 31 Oct 2016 13:47:32 +0000 (+0000) Subject: JAL-98 round when formatting dec places X-Git-Tag: Release_2_11_0~62^2~87 X-Git-Url: http://source.jalview.org/gitweb/?a=commitdiff_plain;h=429df8b06d6a9532ec12d683af22f8246502ca82;p=jalview.git JAL-98 round when formatting dec places --- diff --git a/src/jalview/util/Format.java b/src/jalview/util/Format.java index 7121985..20d228d 100755 --- a/src/jalview/util/Format.java +++ b/src/jalview/util/Format.java @@ -959,7 +959,27 @@ public class Format */ public static void appendPercentage(StringBuilder sb, float value, int dp) { - sb.append((int) value); + /* + * rounding first + */ + double d = value; + long factor = 1L; + for (int i = 0; i < dp; i++) + { + factor *= 10; + } + d *= factor; + d += 0.5; + + /* + * integer part + */ + value = (float) (d / factor); + sb.append((long) value); + + /* + * decimal places + */ if (dp > 0) { sb.append("."); diff --git a/test/jalview/util/FormatTest.java b/test/jalview/util/FormatTest.java index 18199f9..5e49142 100644 --- a/test/jalview/util/FormatTest.java +++ b/test/jalview/util/FormatTest.java @@ -10,23 +10,51 @@ public class FormatTest public void testAppendPercentage() { StringBuilder sb = new StringBuilder(); - Format.appendPercentage(sb, 123.456f, 0); + Format.appendPercentage(sb, 123.436f, 0); assertEquals(sb.toString(), "123"); sb.setLength(0); - Format.appendPercentage(sb, 123.456f, 1); + Format.appendPercentage(sb, 123.536f, 0); + assertEquals(sb.toString(), "124"); + + sb.setLength(0); + Format.appendPercentage(sb, 799.536f, 0); + assertEquals(sb.toString(), "800"); + + sb.setLength(0); + Format.appendPercentage(sb, 123.436f, 1); assertEquals(sb.toString(), "123.4"); sb.setLength(0); - Format.appendPercentage(sb, 123.456f, 2); - assertEquals(sb.toString(), "123.45"); + Format.appendPercentage(sb, 123.436f, 2); + assertEquals(sb.toString(), "123.44"); sb.setLength(0); - Format.appendPercentage(sb, 123.456f, 3); - assertEquals(sb.toString(), "123.456"); + Format.appendPercentage(sb, 123.436f, 3); + assertEquals(sb.toString(), "123.436"); sb.setLength(0); - Format.appendPercentage(sb, 123.456f, 4); - assertEquals(sb.toString(), "123.4560"); + Format.appendPercentage(sb, 123.436f, 4); + assertEquals(sb.toString(), "123.4360"); + } + + @Test(groups = "Functional") + public void testForm_float() + { + Format f = new Format("%3.2f"); + assertEquals(f.form(123f), "123.00"); + assertEquals(f.form(123.1f), "123.10"); + assertEquals(f.form(123.12f), "123.12"); + assertEquals(f.form(123.124f), "123.12"); + assertEquals(f.form(123.125f), "123.13"); + assertEquals(f.form(123.126f), "123.13"); + + f = new Format("%3.0f"); + assertEquals(f.form(123f), "123."); + assertEquals(f.form(12f), "12."); + assertEquals(f.form(123.4f), "123."); + assertEquals(f.form(123.5f), "124."); + assertEquals(f.form(123.6f), "124."); + assertEquals(f.form(129.6f), "130."); } }