From f9cda0832f065ec6a4fe1dd8539b908d03c08896 Mon Sep 17 00:00:00 2001 From: potatoes1286 <48143760+potatoes1286@users.noreply.github.com> Date: Thu, 23 Mar 2023 11:27:09 -0400 Subject: [PATCH] Fix #196 Fixes #196 by preventing divide by percent calculations from being messed with, and adding brackets to fix order of operations --- .../com/darkempire78/opencalculator/Expression.kt | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/darkempire78/opencalculator/Expression.kt b/app/src/main/java/com/darkempire78/opencalculator/Expression.kt index 19385b65..81bc709a 100644 --- a/app/src/main/java/com/darkempire78/opencalculator/Expression.kt +++ b/app/src/main/java/com/darkempire78/opencalculator/Expression.kt @@ -55,6 +55,15 @@ class Expression { if (calculation[operatorBeforePercentPos] == '*') { return calculation } + + if(calculation[operatorBeforePercentPos] == '/') { + // insert brackets into percentage. Fixes 900/10% -> 900/(10/100), not 900/10/100 which evals differently. + // also prevents it from doing the rest of this function, which screws the calculation up + var stringFirst = calculation.substring(0, operatorBeforePercentPos+1) + var stringMiddle = calculation.substring(operatorBeforePercentPos+1, percentPos+1) + var stringLast = calculation.substring(percentPos+1, calculation.length) + return "$stringFirst($stringMiddle)$stringLast" + } // extract the first part of the calculation var calculationStringFirst = calculation.subSequence(0, operatorBeforePercentPos).toString() @@ -279,4 +288,4 @@ class Expression { private fun String.addCharAtIndex(char: Char, index: Int) = StringBuilder(this).apply { insert(index, char) }.toString() -} \ No newline at end of file +}