Fixed crashes on large numbers (#12)

Currently just showing empty conversion result when can not convert due to expression result being too big, just like in Calculator by Google. Will add a proper message later.
This commit is contained in:
Sad Ellie 2022-12-17 13:18:16 +04:00
parent 0a48201595
commit 5cd2b3b205

View File

@ -137,10 +137,17 @@ class MainViewModel @Inject constructor(
// Kotlin doesn't have a multi catch // Kotlin doesn't have a multi catch
val calculatedInput = try { val calculatedInput = try {
val evaluated = Expressions() val evaluated = Expressions()
// Optimal precision, not too low, not too high. Balanced for performance and UX.
.eval(cleanInput) .eval(cleanInput)
.setScale(_userPrefs.value.digitsPrecision, RoundingMode.HALF_EVEN) .setScale(_userPrefs.value.digitsPrecision, RoundingMode.HALF_EVEN)
.stripTrailingZeros() .stripTrailingZeros()
/**
* Too long values crash the UI. If the number is too big, we don't do conversion.
* User probably wouldn't need numbers beyond infinity.
*/
if (evaluated.abs() > BigDecimal.valueOf(Double.MAX_VALUE)) {
_calculatedValue.value = null
return ""
}
if (evaluated.compareTo(BigDecimal.ZERO) == 0) BigDecimal.ZERO else evaluated if (evaluated.compareTo(BigDecimal.ZERO) == 0) BigDecimal.ZERO else evaluated
} catch (e: Exception) { } catch (e: Exception) {
// Kotlin doesn't have a multi catch // Kotlin doesn't have a multi catch