作者:mobiledu2502922357 | 来源:互联网 | 2023-10-13 10:22
使用SpringCloudAlibaba+Vue(ant-design)进行项目开发,一个BigDecimal类型的数,要求保留5位小数。
1、格式化数据 BigDecimal对象格式化可以使用DecimalFormat对象,首先看一下如何解决上述问题
public class BigDecimalTest { public static void main ( String [ ] args) { BigDecimal decimal = new BigDecimal ( 1.5001385 ) ; BigDecimal _decimal = new BigDecimal ( 1.5001 ) ; DecimalFormat decimalFormat = new DecimalFormat ( "0.00000" ) ; String strVal = decimalFormat. format ( decimal) ; System . out. println ( strVal) ; String _strVal = decimalFormat. format ( _decimal) ; System . out. println ( _strVal) ; } }
输出结果:
2、解决返回后补位0消失的问题 完成上述操作后,本以为问题解决了,但是进行接口测试时发现,1.50010通过json返回给接口调用者之后,最后补位的0消失了。 原因 :进行序列化时会使用数字的序列化方式,此时就会将末尾的0舍掉 解决 :使用字符串的序列化方式,在字段对象上面添加注解@JsonFormat(shape = JsonFormat.Shape.STRING)
3、DecimalFormat基本使用 贴一篇文章https://www.jianshu.com/p/b3699d73142e,此处只介绍各种符号及其基本使用
double pi = 3.1415927 ; System . out. println ( new DecimalFormat ( "0" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "0.00" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "00.000" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "#" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "#.##%" ) . format ( pi) ) ; pi= 12.34567 ; System . out. println ( new DecimalFormat ( "0" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "0.00" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "00.000" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "#" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "#.##%" ) . format ( pi) ) ; pi= 12.34 ; System . out. println ( new DecimalFormat ( "6" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "60" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "06" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "00600" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( "#####60000" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".6" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".06" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".60" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".0600" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".6000" ) . format ( pi) ) ; System . out. println ( new DecimalFormat ( ".600000##" ) . format ( pi) ) ;