1.Bigdecimal返回数据小数后0自动被删除的问题
- import com.fasterxml.jackson.core.JsonGenerator;
- import com.fasterxml.jackson.databind.JsonSerializer;
- import com.fasterxml.jackson.databind.SerializerProvider;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- public class BigDecimalSerialize extends JsonSerializer<BigDecimal> {
- @Override
- public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
- if (null != bigDecimal) {
- jsonGenerator.writeString(bigDecimal.setScale(BigDecimal.ROUND_CEILING, RoundingMode.HALF_DOWN).toPlainString() );
- } else {
- jsonGenerator.writeString(BigDecimal.ZERO.toPlainString());
- }
- }
- }
复制代码 在需要处理的字段上使用- @JsonSerialize(using = BigDecimalSerialize.class)
- private BigDecimal amount;
复制代码 2.BigDecimal格式化保留2为小数,不足则补0
- public class NumberFormat {
- public static void main(String[] s){
- System.out.println(formatToNumber(new BigDecimal("3.435")));
- System.out.println(formatToNumber(new BigDecimal(0)));
- System.out.println(formatToNumber(new BigDecimal("0.00")));
- System.out.println(formatToNumber(new BigDecimal("0.001")));
- System.out.println(formatToNumber(new BigDecimal("0.006")));
- System.out.println(formatToNumber(new BigDecimal("0.206")));
- }
- /**
- * @desc 1.0~1之间的BigDecimal小数,格式化后失去前面的0,则前面直接加上0。
- * 2.传入的参数等于0,则直接返回字符串"0.00"
- * 3.大于1的小数,直接格式化返回字符串
- * @param obj传入的小数
- * @return
- */
- public static String formatToNumber(BigDecimal obj) {
- DecimalFormat df = new DecimalFormat("#.00");
- if(obj.compareTo(BigDecimal.ZERO)==0) {
- return "0.00";
- }else if(obj.compareTo(BigDecimal.ZERO)>0&&obj.compareTo(new BigDecimal(1))<0){
- return "0"+df.format(obj).toString();
- }else {
- return df.format(obj).toString();
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |