From 429df8b06d6a9532ec12d683af22f8246502ca82 Mon Sep 17 00:00:00 2001 From: gmungoc Date: Mon, 31 Oct 2016 13:47:32 +0000 Subject: [PATCH] JAL-98 round when formatting dec places --- src/jalview/util/Format.java | 22 ++++++++++++++++++- test/jalview/util/FormatTest.java | 44 ++++++++++++++++++++++++++++++------- 2 files changed, 57 insertions(+), 9 deletions(-) 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."); } } -- 1.7.10.2