-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathdecimal_to_fraction.rs
67 lines (55 loc) · 1.93 KB
/
decimal_to_fraction.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
pub fn decimal_to_fraction(decimal: f64) -> (i64, i64) {
// Calculate the fractional part of the decimal number
let fractional_part = decimal - decimal.floor();
// If the fractional part is zero, the number is already an integer
if fractional_part == 0.0 {
(decimal as i64, 1)
} else {
// Calculate the number of decimal places in the fractional part
let number_of_frac_digits = decimal.to_string().split('.').nth(1).unwrap_or("").len();
// Calculate the numerator and denominator using integer multiplication
let numerator = (decimal * 10f64.powi(number_of_frac_digits as i32)) as i64;
let denominator = 10i64.pow(number_of_frac_digits as u32);
// Find the greatest common divisor (GCD) using Euclid's algorithm
let mut divisor = denominator;
let mut dividend = numerator;
while divisor != 0 {
let r = dividend % divisor;
dividend = divisor;
divisor = r;
}
// Reduce the fraction by dividing both numerator and denominator by the GCD
let gcd = dividend.abs();
let numerator = numerator / gcd;
let denominator = denominator / gcd;
(numerator, denominator)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decimal_to_fraction_1() {
assert_eq!(decimal_to_fraction(2.0), (2, 1));
}
#[test]
fn test_decimal_to_fraction_2() {
assert_eq!(decimal_to_fraction(89.45), (1789, 20));
}
#[test]
fn test_decimal_to_fraction_3() {
assert_eq!(decimal_to_fraction(67.), (67, 1));
}
#[test]
fn test_decimal_to_fraction_4() {
assert_eq!(decimal_to_fraction(45.2), (226, 5));
}
#[test]
fn test_decimal_to_fraction_5() {
assert_eq!(decimal_to_fraction(1.5), (3, 2));
}
#[test]
fn test_decimal_to_fraction_6() {
assert_eq!(decimal_to_fraction(6.25), (25, 4));
}
}