创建:new BigDecimal(stringorint), 创建时使用string或int, 不能用float,double否则会出现精度问题。
后台-前台:bigDecimal前端html显示类型bigDecimal,直接用String报错
`import java.math.BigDecimal
`args BigDecimal price1,BigDecimal price2 // 正确
`args String price1,String price2 //报错
var price1 = Number($('.price1').text());
var price2 = Number($('.price2').text());
alert((price1 + price2).toFixed(2));
public static void test2(BigDecimal price1, BigDecimal price2, BigDecimal price3) {
}
BigDecimal price = new BigDecimal(Double.toString(1.0003));
BigDecimal price2 = new BigDecimal(Double.toString(1.0002));
System.out.println("比较大小:" + price.compareTo(price2));
double d1 = 200.94625d;
double d2 = 100d;
BigDecimal price = new BigDecimal(Double.toString(d1));
BigDecimal price2 = new BigDecimal(Double.toString(d2));
BigDecimal add = price.add(price2);
BigDecimal sub = price.subtract(price2);
BigDecimal mul = price.multiply(price2);
BigDecimal divide = price.divide(price2);
System.out.println(add + "," + (d1+d2));
System.out.println(sub + "," + (d1-d2));
System.out.println(mul + "," + d1*d2);
System.out.println(divide + "," + d1/d2);
结果:
300.94625,300.94624999999996
100.94625,100.94624999999999
20094.625000,20094.625
2.0094625,2.0094624999999997
// 选择国家为中国
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
BigDecimal price = new BigDecimal(Double.toString(123456789.456));
String yuan = nf.format(price);
System.out.println(yuan);
输出结果:
- 自带人民币符号
- 逗号分隔
- 四舍五入,保留两位小数
¥12,356,789.46
BigDecimal price = new BigDecimal(Double.toString(12356789.456));
//NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
DecimalFormat nf = new DecimalFormat("###,##0.00");
String yuan = nf.format(price);
System.out.println(yuan);
输出结果:
- 无人民币符号
- 可以控制显示位数,不足拿0补上(格式化时用#),或者不用拿0补上(格式化用0)
- 四舍五入
12,356,789.46
BigDecimal price = new BigDecimal(Double.toString(0.00796));
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(2); // 小数点后两位,没有补上0
//nf.setMaximumFractionDigits(2); // 小数点后两位,没有不补0
String yuan = nf.format(price);
System.out.println(yuan);
输出结果:
- 结果自动乘以100
- 四舍五入
- nf.setMinimumFractionDigits(2);或nf.setMaximumFractionDigits(2)控制保留位数,否则四舍五入到整数位,如本题为例结果:1%
0.80%
BigDecimal price = new BigDecimal(Double.toString(0.00796));
//NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
DecimalFormat nf = new DecimalFormat("0.##%");
String yuan = nf.format(price);
System.out.println(yuan);
输出结果:
- 结果自动乘以100
- 四舍五入
- 可以控制显示位数,不足拿0补上(格式化时用#),或者不用拿0补上(格式化用0)
0.8%