public class bigDecimalMath {
/**
* 常用方法运算
*/
@Test
public void test1(){
// 使用float会造成精度损失,尽量使用参数类型为String的构造函数。
BigDecimal a = new BigDecimal(0.1);
System.out.println("a = " + a);
System.out.println("=========================");
BigDecimal b = new BigDecimal("0.1");
System.out.println("b = " + b);
BigDecimal c = new BigDecimal("0.8");
System.out.println("b + c = "+c.add(b));
System.out.println("c - b = "+c.subtract(b));
System.out.println("c * b = "+c.multiply(b));
System.out.println("c / b = "+c.divide(b,2));
//求余数
System.out.println("c / b = "+c.remainder(b).setScale(2));
}
/**
* BigDecimal大小比较
*/
@Test
public void test2(){
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.8");
if(b.compareTo(a) > 0){
System.out.println("b的值比a大");
}else if( b.compareTo(a) < 0){
System.out.println("a的值比b大");
}else {
System.out.println("a和b一样大");
}
}
/**
* BigDecimal格式化
*/
@Test
public void test3(){
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
BigDecimal loanAmount = new BigDecimal("15000.48"); //贷款金额
BigDecimal interestRate = new BigDecimal("0.008"); //利率
BigDecimal interest = loanAmount.multiply(interestRate); //相乘
System.out.println("贷款金额:\t" + currency.format(loanAmount));
System.out.println("利率:\t" + percent.format(interestRate));
System.out.println("利息:\t" + currency.format(interest));
}
@Test
public void test4(){
System.out.println(formatToNumber(new BigDecimal("13.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")));
}
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();
}
}
}
BigDecimal常用方法学习
最新推荐文章于 2025-06-02 15:45:12 发布
本文深入探讨了BigDecimal类在Java中的应用,包括精确数学运算、数值比较与格式化等核心功能,并提供了具体示例。
640

被折叠的 条评论
为什么被折叠?



