Skip to content

Commit

Permalink
fix serialize decimal result incorrect, for issue #1831
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Sep 5, 2023
1 parent 5abf262 commit 2e2669d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 24 deletions.
28 changes: 8 additions & 20 deletions core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
}
}

0 comments on commit 2e2669d

Please sign in to comment.