1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use std::fmt;

/// Most of the time, [0, 1]. But some callers may go outside this range.
#[derive(Clone, Copy, PartialEq)]
pub struct Percent(f64);

impl Percent {
    pub fn inner(self) -> f64 {
        self.0
    }

    pub fn int(x: usize) -> Percent {
        if x > 100 {
            panic!("Percent::int({}) too big", x);
        }
        Percent((x as f64) / 100.0)
    }
}

impl fmt::Display for Percent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{:.2}%", self.0 * 100.0)
    }
}