Print exact fractions in conversions

This commit is contained in:
Tiffany Bennett 2016-08-11 22:50:55 -04:00
parent ce1474fd7b
commit 64dd83abc0
2 changed files with 23 additions and 13 deletions

View file

@ -3,7 +3,6 @@ use std::collections::BTreeMap;
use gmp::mpq::Mpq; use gmp::mpq::Mpq;
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use number::{Number, Unit}; use number::{Number, Unit};
use number;
use date; use date;
use unit_defs::DatePattern; use unit_defs::DatePattern;
use std::ops::{Add, Div, Mul, Neg, Sub}; use std::ops::{Add, Div, Mul, Neg, Sub};
@ -365,13 +364,12 @@ impl Context {
Err(String::from_utf8(buf).unwrap()) Err(String::from_utf8(buf).unwrap())
} else { } else {
let raw = &top.0 / &bottom.0; let raw = match &top / &bottom {
let (raw_exact, raw) = number::to_string(&raw); Some(raw) => raw,
let approx = if raw_exact { None => return Err(format!("Division by zero: {} / {}",
format!("") top.show(self), bottom.show(self)))
} else {
format!("approx. ")
}; };
let number = raw.show_number_part();
let mut unit_top = vec![]; let mut unit_top = vec![];
let mut unit_frac = vec![]; let mut unit_frac = vec![];
for (name, exp) in bottom_name.into_iter() { for (name, exp) in bottom_name.into_iter() {
@ -408,8 +406,8 @@ impl Context {
(false, v) => v, (false, v) => v,
(true, v) => format!("1 / {}", v) (true, v) => format!("1 / {}", v)
}; };
Ok(format!("{approx}{raw}{unit_top}{unit_frac} ({reduced})", Ok(format!("{number}{unit_top}{unit_frac} ({reduced})",
approx=approx, raw=raw, unit_top=unit_top, number=number, unit_top=unit_top,
unit_frac=unit_frac, reduced=reduced)) unit_frac=unit_frac, reduced=reduced))
} }
}, },

View file

@ -220,14 +220,11 @@ impl Number {
Err(format!("Exponent must be either an integer or the reciprocal of an integer")) Err(format!("Exponent must be either an integer or the reciprocal of an integer"))
} }
} }
}
impl Show for Number { pub fn show_number_part(&self) -> String {
fn show(&self, context: &::eval::Context) -> String {
use std::io::Write; use std::io::Write;
let mut out = vec![]; let mut out = vec![];
let mut frac = vec![];
let mut value = self.clone(); let mut value = self.clone();
value.0.canonicalize(); value.0.canonicalize();
@ -244,6 +241,21 @@ impl Show for Number {
if let Some(approx) = approx { if let Some(approx) = approx {
write!(out, ", approx. {}", approx).unwrap(); write!(out, ", approx. {}", approx).unwrap();
} }
String::from_utf8(out).unwrap()
}
}
impl Show for Number {
fn show(&self, context: &::eval::Context) -> String {
use std::io::Write;
let mut out = vec![];
let mut frac = vec![];
let mut value = self.clone();
value.0.canonicalize();
write!(out, "{}", self.show_number_part()).unwrap();
for (&dim, &exp) in &value.1 { for (&dim, &exp) in &value.1 {
if exp < 0 { if exp < 0 {
frac.push((dim, exp)); frac.push((dim, exp));