-
Notifications
You must be signed in to change notification settings - Fork 478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG]JSON序列化,BigDecimal值不对。 #1831
Comments
感觉像是这个方法的问题:com.alibaba.fastjson2.util.IOUtils.writeDecimal IOUtils.writeDecimal如果修改成这样,可以解决上面的问题,而且效率会更高: public static int writeDecimal(byte[] buf, int off, long unscaledVal, int scale) {
if (unscaledVal < 0) {
buf[off++] = '-';
unscaledVal = -unscaledVal;
}
if (scale > 0) {
boolean s = false;
// 整数部分
for (int i = POWER_TEN.length - 1; i >= 0; i--) {
if (i == scale - 2) {
break;
}
byte c = '0';
while (unscaledVal >= POWER_TEN[i]) {
unscaledVal -= POWER_TEN[i];
c++;
}
if (c > '0') {
s = true;
}
if (s) {
buf[off++] = c;
}
}
if (!s) {
buf[off++] = '0';
}
// 小数部分
if (unscaledVal > 0) {
buf[off++] = '.';
for (int i = scale - 2; i >= 0; i--) {
if (unscaledVal == 0) {
break;
}
byte c = '0';
while (unscaledVal >= POWER_TEN[i]) {
unscaledVal -= POWER_TEN[i];
c++;
}
buf[off++] = c;
}
if (unscaledVal > 0) {
buf[off++] = (byte) ('0' + unscaledVal);
}
}
} else {
boolean s = false;
for (int i = POWER_TEN.length - 1; i >= 0; i--) {
byte c = '0';
while (unscaledVal >= POWER_TEN[i]) {
unscaledVal -= POWER_TEN[i];
c++;
}
if (c > '0') {
s = true;
}
if (s) {
buf[off++] = c;
}
}
buf[off++] = (byte) ('0' + unscaledVal);
for (int i = scale; i < 0; i++) {
buf[off++] = '0';
}
}
return off;
}
// @formatter:off
static final long[] POWER_TEN = {
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000L,
100000000000L,
1000000000000L,
10000000000000L,
100000000000000L,
1000000000000000L,
10000000000000000L,
100000000000000000L,
1000000000000000000L,
};
// @formatter:off |
https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson2/fastjson2/2.0.40-SNAPSHOT/ |
有benchmark数据么? |
没有, |
2.0.41-SNAPSHOT版本中已解决。 |
问题描述
JSON序列化,BigDecimal值不对。
new BigDecimal("1.09600000")序列化JSON的值变成了:1.9600000
环境信息
FastJson2版本:2.0.40
JDK版本:1.8
系统:linux与window都可以再现
重现步骤
测试代码如下:
输出的结果是:{"goodsWeight":1.9600000}
"1.09600000"变成了:1.9600000
另外,一个建议:BigDecimal转换成String时,默认是否可以这样转换:
BigDecimal dec = new BigDecimal("1.09600000");
String str = dec.stripTrailingZeros().toPlainString();
The text was updated successfully, but these errors were encountered: