Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Issue #10) num_rational::Ratio: Add the ability to format as a decimal #37

Closed
wants to merge 5 commits into from
Closed
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,14 @@ impl<T: Clone + Integer + Signed> Signed for Ratio<T> {
}
}

#[cfg(feature = "std")]
use std::string::String;

#[cfg(feature = "std")]
trait AsDecimal {
Hazardius marked this conversation as resolved.
Show resolved Hide resolved
fn as_decimal(&self, usize) -> String;
}

// String conversions
impl<T> fmt::Display for Ratio<T>
where
Expand All @@ -993,6 +1001,48 @@ where
}
}

#[cfg(feature = "std")]
impl<T> AsDecimal for Ratio<T> where
T: fmt::Display
+ Clone
+ Eq
Hazardius marked this conversation as resolved.
Show resolved Hide resolved
+ FromPrimitive
+ Integer
+ Pow<usize, Output = T>
Hazardius marked this conversation as resolved.
Show resolved Hide resolved
+ Signed
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need Signed?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure that I've added it to be able to use fn abs(&self).
Couldn't find a way to drop it now.

+ std::string::ToString,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is implied by Display.
(via impl<T> ToString for T where T: Display)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got rid of it from the type traits, but needed to add use std::string::ToString; elsewhere to make it compile.

{
/// Generates decimal approximation to a specified precision as a String.
fn as_decimal(&self, precision: usize) -> String {
if self.denom.is_one() {
self.numer.to_string()
} else {
let _10_pow_prec = T::from_usize(10).unwrap().pow(precision);
let rounded = (self.clone() * &_10_pow_prec).round();
let minus = rounded < Zero::zero();
let trunc = &((&rounded / &_10_pow_prec).trunc().to_integer());
let tail = &(rounded % _10_pow_prec).abs().to_integer();
if tail.is_zero() {
trunc.to_string()
} else {
let mut ret_val = String::from(if minus { "-" } else { "" });
ret_val.push_str(&trunc.to_string());
ret_val.push_str(".");
let tail_strarr = &tail.to_string();
let tail_length = &tail_strarr.chars().count();
let tail_zeroes = if tail_length < &precision {
// If rust >= 1.16.0 - we can simply use repeat.
// "0".repeat(precision - tail_length)
(0..(precision - tail_length)).map(|_| "0").collect::<String>()
} else { String::from("") };
ret_val.push_str(&tail_zeroes);
ret_val.push_str(&tail.to_string());
ret_val
}
}
}
}

impl<T: FromStr + Clone + Integer> FromStr for Ratio<T> {
type Err = ParseRatioError;

Expand Down Expand Up @@ -1352,6 +1402,19 @@ mod test {
numer: -2,
denom: 3,
};
pub const _1_8: Rational = Ratio { numer: 1, denom: 8 };
pub const _NEG1_8: Rational = Ratio {
numer: -1,
denom: 8,
};
pub const _99999_1000: Rational = Ratio {
numer: 99999,
denom: 1000,
};
pub const _NEG99999_1000: Rational = Ratio {
numer: -99999,
denom: 1000,
};

#[cfg(feature = "bigint")]
pub fn to_big(n: Rational) -> BigRational {
Expand Down Expand Up @@ -1536,6 +1599,22 @@ mod test {
assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
}

#[test]
#[cfg(feature = "std")]
fn test_as_decimal() {
use AsDecimal;
use std::string::ToString;
assert_eq!(_2.as_decimal(2), "2".to_string());
Hazardius marked this conversation as resolved.
Show resolved Hide resolved
assert_eq!(_1_2.as_decimal(2), "0.50".to_string());
assert_eq!(_3_2.as_decimal(1), "1.5".to_string());
assert_eq!(_NEG1_2.as_decimal(2), "-0.50".to_string());
assert_eq!(_NEG2_3.as_decimal(3), "-0.667".to_string());
assert_eq!(_1_8.as_decimal(2), "0.13".to_string());
assert_eq!(_NEG1_8.as_decimal(4), "-0.1250".to_string());
assert_eq!(_99999_1000.as_decimal(3), "99.999".to_string());
assert_eq!(_NEG99999_1000.as_decimal(1), "-100".to_string());
Hazardius marked this conversation as resolved.
Show resolved Hide resolved
}

mod arith {
use super::super::{Ratio, Rational};
use super::{_0, _1, _1_2, _2, _3_2, _NEG1_2, to_big};
Expand Down