From: Robert Varga Date: Tue, 24 May 2022 12:21:26 +0000 (+0200) Subject: Fix Decimal64.toString() X-Git-Tag: v8.0.6~7 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=commitdiff_plain;h=refs%2Fchanges%2F74%2F101274%2F1;p=yangtools.git Fix Decimal64.toString() intPart() does not carry the sign when the leading part is zero, hence we need to adjust for that. JIRA: YANGTOOLS-1438 Change-Id: I5049650b0997e6543455542d48b3f2dcdd02bc4c Signed-off-by: Robert Varga (cherry picked from commit 59b48fd2b49f11a6381fa0e1cacb20e447a23924) --- diff --git a/common/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/Decimal64.java b/common/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/Decimal64.java index c91e42f417..bd62d8aaaa 100644 --- a/common/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/Decimal64.java +++ b/common/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/Decimal64.java @@ -448,11 +448,18 @@ public class Decimal64 extends Number implements CanonicalValue { // prohibited, subject to the rule that there MUST be at least one digit // before and after the decimal point. The value zero is represented as // "0.0". - final StringBuilder sb = new StringBuilder(21).append(intPart()).append('.'); + + final long intPart = intPart(); final long fracPart = fracPart(); + final StringBuilder sb = new StringBuilder(21); + if (intPart == 0 && fracPart < 0) { + sb.append('-'); + } + sb.append(intPart).append('.'); + if (fracPart != 0) { // We may need to zero-pad the fraction part - sb.append(Strings.padStart(Long.toString(fracPart), scale(), '0')); + sb.append(Strings.padStart(Long.toString(Math.abs(fracPart)), scale(), '0')); } else { sb.append('0'); } @@ -502,7 +509,7 @@ public class Decimal64 extends Number implements CanonicalValue { } private long fracPart() { - return Math.abs(value % FACTOR[offset]); + return value % FACTOR[offset]; } private static byte offsetOf(final int scale) { diff --git a/common/yang-common/src/test/java/org/opendaylight/yangtools/yang/common/Decimal64Test.java b/common/yang-common/src/test/java/org/opendaylight/yangtools/yang/common/Decimal64Test.java index c0440f0de8..9aae74a276 100644 --- a/common/yang-common/src/test/java/org/opendaylight/yangtools/yang/common/Decimal64Test.java +++ b/common/yang-common/src/test/java/org/opendaylight/yangtools/yang/common/Decimal64Test.java @@ -223,6 +223,11 @@ public class Decimal64Test { assertEquals("-1.0", Decimal64.valueOf(BigDecimal.ONE.negate()).toString()); } + @Test + public void testLeadingZeroToString() { + assertEquals("-0.63", Decimal64.valueOf("-0.63").toString()); + } + @Test public void testBoundaries() { assertEquals(-128L, Decimal64.valueOf(1, Byte.MIN_VALUE).longValue());