数据计算规范

  • 数据计算方法
  • 数值格式化方法

所有float和double类型的加减乘除都不能直接算,包括乘以10除以10等操作,举个错误的栗子:

1
2
3
> > > double a = 99.9,b = -9.99;
> > > System.out.println("a+b="+(a+b));
> > >

输出89.910000.....

1
2
3
> > > double a = 99.9,b = 9.99;
> > > System.out.println("a-b="+(a-b));
> > >

输出89.910000.....

乘除

1
2
3
4
> > > double a = 11.1,b = 9;
> > > System.out.println("a*b="+(a*b));
> > > System.out.println("a/b="+(a/b));
> > >

输出

1
2
3
> > >99.89999.....
> > >1.233333.....
> > >

所以,所有数值运算必须转换为成BigDecimal,这个类是专门处理精度运算的。
这里封装在DataUtility中,做数值运算时直接调用addsubtractmultiplydivide方法。
还有一个需要注意的就是调用这个方法后返回值的赋值问题,比如返回一个float,赋值给double,这个时候系统的自动强转是肯定出错的(除了整数),所以一定要注意返回值,或者使用DataUtility的强转方法。

具体方法如下图,运算的精度原则是四舍五入。

描述 方法名 参数 举例
加法(默认精确2位) add (double… numbers)等,参数会逐个向后累加 add(1,2,3),结果为6.00
加法(带精度) add (int scale, double… numbers) add(1,2,3),结果为5.0
减法(默认精确2位) subtract (double… numbers)等,参数会逐个向后做减法 subtract(10,2,3),结果为5.00
减法(带精度) add (int scale, double… numbers) subtract(1,10,2,3),结果为5.0
乘法 multiply (double… numbers)等,参数会逐个向后做乘法 multiply(10,2,3),结果为60.00
乘法(带精度) multiply (int scale, double… numbers) multiply(1,10,2,3),结果为60.0
除法 divide (double… numbers)等,参数会逐个向后做除法 divide(10,2,3),结果为1.67
除法(带精度) divide (int scale, double… numbers) divide(10,2,3),结果为1.7
取余 remainder (double number)等,取余,两个参数 remainder(5,3),结果为2
强转为int castToInt (double number) castToInt(5.7),结果为6;castToInt(5.4),结果为5
强转为long castToLong (double number) castToLong(5.7),结果为6;castToInt(5.4),结果为5
强转为float castToFloat (double number) castToFloat(5.7),结果为5.7
强转为double castToDouble (float number) castToDouble(5.7),结果为5.7

数值格式化

数值格式化方法封装在AsdUtility中。

不保留0

如果小数位最后一位是0则不保留,

1
2
3
4
String formatNumber(double number, int scale) //指定精度
String formatNumber(double number) //默认精度是2
String formatNumber(float number, int scale) //指定精度
String formatNumber(float number) //默认精度是2

保留0

保留小数位的0。

1
2
String formatNumberByLen(double number, int len)
String formatNumberByLen(float number, int len)
如果您觉得这篇文章不错,可以打赏支持下哦,谢谢