From ba2a840a28fb70dd41ce91d2746ab55a836c2a12 Mon Sep 17 00:00:00 2001 From: bakk Date: Sat, 22 Jan 2022 02:21:16 +0100 Subject: [PATCH] Fixed panic for numbers like 6.6666667 --- kalk/src/kalk_value/rounding.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/kalk/src/kalk_value/rounding.rs b/kalk/src/kalk_value/rounding.rs index 57be728..885256d 100644 --- a/kalk/src/kalk_value/rounding.rs +++ b/kalk/src/kalk_value/rounding.rs @@ -115,13 +115,17 @@ fn equivalent_fraction(value: f64) -> Option { // https://goodcalculators.com/repeating-decimal-to-fraction-conversion-calculator/ let (mut numer, mut denom) = if let Some(repeatend_str) = find_repeatend(&abs_value_str) { - let repeatend_pos = abs_value_str.find(&repeatend_str)?; - let non_repeating_str = &abs_value_str[..repeatend_pos]; + let dot_pos = abs_value_str.find('.')?; + let repeatend_pos = abs_value_str[dot_pos..].find(&repeatend_str)? + dot_pos; + let non_repeating_str = &abs_value_str[..repeatend_pos].trim_end_matches('.'); // non-repeating let non_repeating = non_repeating_str.parse::().unwrap_or(0f64); - let non_repeating_dec_count = - non_repeating_str.len() - non_repeating_str.find('.').unwrap_or(0) - 1; + let non_repeating_dec_count = if let Some(dot_pos) = non_repeating_str.find('.') { + non_repeating_str.len() - dot_pos - 1 + } else { + 0 + }; let a = non_repeating.fract(); // repeatend