fixing some percentage related operations

This commit is contained in:
tibbi
2018-08-09 23:29:01 +02:00
parent 179982e238
commit 2f18de44a3
2 changed files with 12 additions and 2 deletions

View File

@@ -13,6 +13,7 @@ class CalculatorImpl(calculator: Calculator, val context: Context) {
private var mIsFirstOperation = false private var mIsFirstOperation = false
private var mResetValue = false private var mResetValue = false
private var mWasPercentLast = false
private var mBaseValue = 0.0 private var mBaseValue = 0.0
private var mSecondValue = 0.0 private var mSecondValue = 0.0
@@ -58,7 +59,11 @@ class CalculatorImpl(calculator: Calculator, val context: Context) {
if (sign == "") { if (sign == "") {
setFormula(sign + first) setFormula(sign + first)
} else if (!sign.isEmpty()) { } else if (!sign.isEmpty()) {
setFormula(first + sign + second) var formula = first + sign + second
if (mWasPercentLast) {
formula += "%"
}
setFormula(formula)
} }
} }
@@ -99,6 +104,10 @@ class CalculatorImpl(calculator: Calculator, val context: Context) {
private fun calculateResult() { private fun calculateResult() {
updateFormula() updateFormula()
if (mWasPercentLast) {
mSecondValue *= mBaseValue / 100
}
val operation = OperationFactory.forId(mLastOperation!!, mBaseValue, mSecondValue) val operation = OperationFactory.forId(mLastOperation!!, mBaseValue, mSecondValue)
if (operation != null) { if (operation != null) {
updateResult(operation.getResult()) updateResult(operation.getResult())
@@ -108,6 +117,7 @@ class CalculatorImpl(calculator: Calculator, val context: Context) {
} }
fun handleOperation(operation: String) { fun handleOperation(operation: String) {
mWasPercentLast = operation == PERCENT
if (lastKey == DIGIT && operation != ROOT) { if (lastKey == DIGIT && operation != ROOT) {
handleResult() handleResult()
} }

View File

@@ -8,7 +8,7 @@ class PercentOperation(baseValue: Double, secondValue: Double) : BinaryOperation
override fun getResult(): Double { override fun getResult(): Double {
var result = 0.0 var result = 0.0
if (secondValue != 0.0) { if (secondValue != 0.0) {
result = (baseValue / 100) * secondValue result = baseValue / 100 * secondValue
} }
return result return result
} }