Skip to content

Commit

Permalink
fix BigDecimal error,for issue alibaba#1831
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielHwang committed Sep 5, 2023
1 parent dfb3ff7 commit 506b930
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
7 changes: 7 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ public static int writeDecimal(char[] buf, int off, long unscaledVal, int scale)
long power = POWER_TEN[scale - 1];
long div = unscaledVal / power;
long rem = unscaledVal - div * power;
int remSize = stringSize(rem);
off = IOUtils.writeInt64(buf, off, div);
buf[off] = '.';
if (scale == 1) {
Expand All @@ -373,6 +374,12 @@ public static int writeDecimal(char[] buf, int off, long unscaledVal, int scale)
buf[off + 2] = (char) (v >> 32);
buf[off + 3] = (char) (v >> 48);
return off + 4;
}else {
int temp = remSize;
while (temp < scale) {
buf[++off] = '0';
temp++;
}
}
return IOUtils.writeInt64(buf, off + 1, rem);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.alibaba.fastjson2.issues_1800;

import com.alibaba.fastjson2.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.junit.jupiter.api.Test;

import java.io.Serializable;
import java.math.BigDecimal;

import static org.junit.Assert.assertEquals;

public class Issue1831 {

@Getter
@Setter
@ToString
public static class TestCls
implements Serializable {
private static final long serialVersionUID = 1L;
private BigDecimal goodsWeight;
private BigDecimal mineGrossWeight;
private BigDecimal mineTareWeight;
private BigDecimal mineWeighBridgeNet;
private BigDecimal mineNetBeforeSapmle;
private BigDecimal mineNetAfterSapmle;
}
@Test
public void Test() {
TestCls bean = new TestCls();
bean.setGoodsWeight(new BigDecimal("1.0009600000"));
bean.setMineGrossWeight(new BigDecimal("1.0"));
bean.setMineNetAfterSapmle(new BigDecimal("10.9600000"));
bean.setMineNetBeforeSapmle(new BigDecimal("1.096"));
bean.setMineWeighBridgeNet(new BigDecimal(".103"));
String expected = "{\"goodsWeight\":1.0009600000,\"mineGrossWeight\":1.0," +
"\"mineNetAfterSapmle\":10.9600000,\"mineNetBeforeSapmle\":1.096,\"" +
"mineWeighBridgeNet\":0.103}";
assertEquals(expected, JSONObject.toJSONString(bean));
}
}

0 comments on commit 506b930

Please sign in to comment.