Function fraction::division::divide_to_writeable

source ·
pub fn divide_to_writeable<I>(
    writeable: &mut dyn Write,
    dividend: I,
    divisor: I,
    precision: usize,
    trail_zeroes: bool,
) -> Result<I, DivisionError>
where I: Clone + GenericInteger,
Expand description

Divide a fraction into a writeable target implementing std::fmt::Write
Returns the remainder of the division

  • No allocations
  • Does not round the last digit

Makes the division and puts the result into the formatter. Uses divide_integral and divide_rem functions internally.

WARNING: Negative numbers as arguments are not supported.

§Examples

use fraction::division::{ divide_to_writeable, division_result_max_char_length };

let num = 7;
let denom = 4;

let mut string = String::with_capacity(division_result_max_char_length(&num, 2));

divide_to_writeable(&mut string, num, denom, 2, false).ok();

assert_eq!(string, "1.75");
use fraction::division::divide_to_writeable;

use std::fmt;

struct Foo(i32, i32);

impl fmt::Display for Foo {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let precision = formatter.precision().unwrap_or(2);
        match divide_to_writeable(formatter, self.0, self.1, precision, false) {
            Err(_) => Err(fmt::Error),
            _ => Ok(())
        }
    }
}

assert_eq! (format!("{}", Foo(1, 2)), "0.5");
assert_eq! (format!("{:.3}", Foo(1, 3)), "0.333");
assert_eq! (format!("{:.16}", Foo(5, 7)), "0.7142857142857142");