gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:28:34 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com