fix #237, fixing some weird Double rounding error at plus and minus

This commit is contained in:
tibbi 2022-02-11 20:53:19 +01:00
parent f3c063dd01
commit 235213a985
2 changed files with 14 additions and 2 deletions

View file

@ -62,7 +62,7 @@ android {
}
dependencies {
implementation 'com.github.SimpleMobileTools:Simple-Commons:178537ae0d'
implementation 'com.github.SimpleMobileTools:Simple-Commons:03e4d214b1'
implementation 'me.grantland:autofittextview:0.2.1'
implementation 'net.objecthunter:exp4j:0.4.8'

View file

@ -6,6 +6,7 @@ import com.simplemobiletools.calculator.models.History
import com.simplemobiletools.commons.extensions.showErrorToast
import com.simplemobiletools.commons.extensions.toast
import net.objecthunter.exp4j.ExpressionBuilder
import java.math.BigDecimal
class CalculatorImpl(calculator: Calculator, private val context: Context) {
private var callback: Calculator? = calculator
@ -239,7 +240,18 @@ class CalculatorImpl(calculator: Calculator, private val context: Context) {
val second = secondValue / 100f
ExpressionBuilder("${baseValue.format().replace(",", "")}*${second.format()}").build().evaluate()
} else {
ExpressionBuilder(expression.replace(",", "")).build().evaluate()
// avoid Double rounding errors at expressions like 5250,74 + 14,98
if (sign == "+" || sign == "-") {
val first = BigDecimal.valueOf(baseValue)
val second = BigDecimal.valueOf(secondValue)
val bigDecimalResult = when (sign) {
"-" -> first.minus(second)
else -> first.plus(second)
}
bigDecimalResult.toDouble()
} else {
ExpressionBuilder(expression.replace(",", "")).build().evaluate()
}
}
if (result.isInfinite() || result.isNaN()) {