fixing another usecase of percentage

This commit is contained in:
tibbi 2021-11-15 20:37:36 +01:00
parent 0a6a49c17c
commit 14bb42c832

View File

@ -93,23 +93,27 @@ class CalculatorImpl(calculator: Calculator, private val context: Context) {
} }
if (lastKey == DIGIT || lastKey == DECIMAL) { if (lastKey == DIGIT || lastKey == DECIMAL) {
// split to multiple lines just to see when does the crash happen if (lastOperation != "" && operation == PERCENT) {
secondValue = when (operation) { handlePercent()
PLUS -> getSecondValue() } else {
MINUS -> getSecondValue() // split to multiple lines just to see when does the crash happen
MULTIPLY -> getSecondValue() secondValue = when (operation) {
DIVIDE -> getSecondValue() PLUS -> getSecondValue()
ROOT -> getSecondValue() MINUS -> getSecondValue()
POWER -> getSecondValue() MULTIPLY -> getSecondValue()
PERCENT -> getSecondValue() DIVIDE -> getSecondValue()
else -> getSecondValue() ROOT -> getSecondValue()
} POWER -> getSecondValue()
PERCENT -> getSecondValue()
else -> getSecondValue()
}
calculateResult() calculateResult()
if (!operations.contains(inputDisplayedFormula.last().toString())) { if (!operations.contains(inputDisplayedFormula.last().toString())) {
if (!inputDisplayedFormula.contains("÷")) { if (!inputDisplayedFormula.contains("÷")) {
inputDisplayedFormula += getSign(operation) inputDisplayedFormula += getSign(operation)
}
} }
} }
} }
@ -138,6 +142,20 @@ class CalculatorImpl(calculator: Calculator, private val context: Context) {
return false return false
} }
// handle percents manually, it doesn't seem to be possible via net.objecthunter:exp4j. "%" is used only for modulo there
// handle cases like 10+200% here
private fun handlePercent() {
var result = calculatePercentage(baseValue, getSecondValue(), lastOperation)
if (result.isInfinite() || result.isNaN()) {
result = 0.0
}
showNewFormula("${baseValue.format()}${getSign(lastOperation)}${getSecondValue().format()}%")
inputDisplayedFormula = result.format()
showNewResult(result.format())
baseValue = result
}
fun handleEquals() { fun handleEquals() {
if (lastKey == EQUALS) { if (lastKey == EQUALS) {
calculateResult() calculateResult()
@ -203,6 +221,7 @@ class CalculatorImpl(calculator: Calculator, private val context: Context) {
} }
// handle percents manually, it doesn't seem to be possible via net.objecthunter:exp4j. "%" is used only for modulo there // handle percents manually, it doesn't seem to be possible via net.objecthunter:exp4j. "%" is used only for modulo there
// handle cases like 10%200 here
val result = if (sign == "%") { val result = if (sign == "%") {
val second = secondValue / 100f val second = secondValue / 100f
ExpressionBuilder("${baseValue.format()}*${second.format()}").build().evaluate() ExpressionBuilder("${baseValue.format()}*${second.format()}").build().evaluate()