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 all 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
69 changes: 69 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,47 @@ where
}
}

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

#[cfg(feature = "std")]
impl<T> Ratio<T> where
T: fmt::Display
+ Clone
+ FromPrimitive
+ Integer
+ 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.

{
/// Generates decimal approximation to a specified precision as a String.
pub fn as_decimal(&self, precision: usize) -> String {
use traits::pow;
use std::string::ToString;
let ten_pow_prec = pow(T::from_usize(10).unwrap(), precision);
let rounded = (self.clone() * &ten_pow_prec).round();
let minus = rounded < Zero::zero();
let trunc = &((&rounded / &ten_pow_prec).trunc().to_integer());
let tail = &(rounded % ten_pow_prec).abs().to_integer();
let mut ret_val = String::from("");
if tail.is_zero() {
ret_val.push_str(&trunc.to_string());
} else {
if minus { ret_val.push_str("-") };
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 +1393,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 +1590,21 @@ mod test {
assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string());
}

#[test]
#[cfg(feature = "std")]
fn test_as_decimal() {
use std::string::ToString;
assert_eq!(_2.as_decimal(2), "2.00".to_string());
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.0".to_string());
}

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