// 在Java中处理金额时,推荐使用BigDecimal类型,因为它可以精确表示和计算货币值,避免浮点数精度问题。
import java.math.BigDecimal;
public class AmountExample {
public static void main(String[] args) {
// 创建BigDecimal对象表示金额
BigDecimal amount1 = new BigDecimal("123.45");
BigDecimal amount2 = new BigDecimal("67.89");
// 金额相加
BigDecimal total = amount1.add(amount2);
System.out.println("Total: " + total);
// 金额相减
BigDecimal difference = amount1.subtract(amount2);
System.out.println("Difference: " + difference);
// 金额相乘
BigDecimal product = amount1.multiply(amount2);
System.out.println("Product: " + product);
// 金额相除(注意:除法需要指定精度和舍入模式)
BigDecimal quotient = amount1.divide(amount2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("Quotient: " + quotient);
}
}
new BigDecimal("123.45")
使用字符串来创建 BigDecimal 对象,以确保不会引入浮点数的精度误差。上一篇:java命名
下一篇:java fork join
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站