java - 为什么在 Java 中进行交易之前要与 BigDecimal.ONE 比较余额?

标签 java transactions compare bigdecimal compareto

我正在查看有关从一个帐户到另一个帐户的金融交易的教程,在将金额从一个帐户转移到另一个帐户之前,他们会进行以下两个比较:

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
                && fromAccount.getCurrentBalance().compareTo(amount) == 1

我明白他们进行第二次比较是为了将余额与金额进行比较,但我不明白的是他们为什么将余额与 BigDecimal.ONE 进行比较。有人可以解释一下吗?

我不明白这个比较是什么:

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE)

这是代码:

if(fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
        && fromAccount.getCurrentBalance().compareTo(amount) == 1
){
    fromAccount.setCurrentBalance(fromAccount.getCurrentBalance().subtract(amount));
    accountRepository.save(fromAccount);
    toAccount.setCurrentBalance(toAccount.getCurrentBalance().add(amount));
    accountRepository.save(toAccount);
    Transaction transaction = transactionRepository.save(new Transaction(0L,fromAccountNumber,amount,new Timestamp(System.currentTimeMillis())));
    return transaction;
}
return null;

最佳答案

这只是一个BigDecimal大于java中的条件签名。如果您CurrentBalance变量数据类型为BigDecimal那么你就不能使用普通的整数条件签名,如 ==><BigDecimal compareTo()方法返回值以确定 equal , greater thanless than操作。

Big Decimal CompareTo() 方法返回

0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.

如果我们考虑这条线

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1

这行可以简单地表示整数数据类型

if(fromAccount.getCurrentBalance() > 1)

如果我将您的两个条件转换为正常的整数数据类型操作,那么它将如下所示。

if(fromAccount.getCurrentBalance() > 1 && fromAccount.getCurrentBalance() > amount)

访问此处了解BigDecimal compareTo()操作。
https://www.geeksforgeeks.org/bigdecimal-compareto-function-in-java/

关于java - 为什么在 Java 中进行交易之前要与 BigDecimal.ONE 比较余额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62103909/

相关文章:

java - 重构 if-else 控制流程

java - 版本字段打破了持久层上的 orphanRemoval 行为

qt多个QSqlTableModels在一个事务中一起编辑

java - 事务未回滚

vb.net - 有条件地检查 GetType() 容器中的值类型

java - 从 Java 6 SE 迁移到 Java 6 EE

java - jetty.xml 在 Maven 项目中的位置?

spring-boot - 在采用过时值的事务中执行的 Spring native 查询

go - 如何比较嵌套结构,在子 slice 字段中具有相同字段但顺序不同

android - 将 List<String> 项与 String 进行比较