diff --git a/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java b/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java index b15e411cac..91360dfa46 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java @@ -317,22 +317,16 @@ public static int writeDecimal(byte[] buf, int off, long unscaledVal, int scale) off = IOUtils.writeInt64(buf, off, div); buf[off] = '.'; - for (int i = 0, end = unscaleValSize - stringSize(rem) - insertionPoint; i < end; ++i) { - buf[++off] = '0'; - } - if (scale == 1) { buf[off + 1] = (byte) (rem + '0'); return off + 2; } else if (scale == 2) { UNSAFE.putShort(buf, ARRAY_BYTE_BASE_OFFSET + off + 1, PACKED_DIGITS[(int) rem]); return off + 3; - } else if (scale == 3) { - int v = DIGITS_K_32[(int) rem]; - buf[off + 1] = (byte) (v >> 8); - buf[off + 2] = (byte) (v >> 16); - buf[off + 3] = (byte) (v >> 24); - return off + 4; + } + + for (int i = 0, end = unscaleValSize - stringSize(rem) - insertionPoint; i < end; ++i) { + buf[++off] = '0'; } return IOUtils.writeInt64(buf, off + 1, rem); } @@ -369,22 +363,16 @@ public static int writeDecimal(char[] buf, int off, long unscaledVal, int scale) off = IOUtils.writeInt64(buf, off, div); buf[off] = '.'; - for (int i = 0, end = unscaleValSize - stringSize(rem) - insertionPoint; i < end; ++i) { - buf[++off] = '0'; - } - if (scale == 1) { buf[off + 1] = (char) (rem + '0'); return off + 2; } else if (scale == 2) { UNSAFE.putInt(buf, ARRAY_CHAR_BASE_OFFSET + ((off + 1) << 1), PACKED_DIGITS_UTF16[(int) rem]); return off + 3; - } else if (scale == 3) { - long v = DIGITS_K_64[(int) rem]; - buf[off + 1] = (char) (v >> 16); - buf[off + 2] = (char) (v >> 32); - buf[off + 3] = (char) (v >> 48); - return off + 4; + } + + for (int i = 0, end = unscaleValSize - stringSize(rem) - insertionPoint; i < end; ++i) { + buf[++off] = '0'; } return IOUtils.writeInt64(buf, off + 1, rem); } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_1800/Issue1831.java b/core/src/test/java/com/alibaba/fastjson2/issues_1800/Issue1831.java index 47978745c3..1eb4d5a3fa 100644 --- a/core/src/test/java/com/alibaba/fastjson2/issues_1800/Issue1831.java +++ b/core/src/test/java/com/alibaba/fastjson2/issues_1800/Issue1831.java @@ -10,9 +10,19 @@ public class Issue1831 { @Test public void test() { - String str = "1.09600000"; - BigDecimal decimal = new BigDecimal(str); - assertEquals(str, JSON.toJSONString(decimal)); - assertEquals(str, new String(JSON.toJSONBytes(decimal))); + String[] strings = new String[] { + "1.6", + "1.06", + "1.66", + "1.096", + "1.696", + "1.09600000", + "1.096000001" + }; + for (String str : strings) { + BigDecimal decimal = new BigDecimal(str); + assertEquals(str, JSON.toJSONString(decimal)); + assertEquals(str, new String(JSON.toJSONBytes(decimal))); + } } }