···5858 Ok(())
5959}
60606161+/// Limit the sig figs (precision) of the number
6262+fn round_to_sig_figs(x: D128, sig_figs: i32) -> D128 {
6363+ if x.is_zero() {
6464+ return x;
6565+ }
6666+ let mag: i32 = x.log10().floor().try_into().unwrap();
6767+ let shift = sig_figs - 1 - mag;
6868+ let factor = D128::TEN.powi(shift);
6969+ (x * factor).round(0) / factor
7070+}
7171+6172/// Get the exchange rate from one currency to another
6273/// Both currencies must be currency units
6374pub fn get_exchange_rate(from: Unit, to: Unit) -> Result<D128, String> {
···8091 .get(&to)
8192 .ok_or_else(|| format!("No exchange rate found for {:?}", to))?;
82938383- // Convert from -> EUR -> to
8484- // rate = (to / EUR) / (from / EUR) = to / from
8585- Ok(*to_rate / *from_rate)
9494+ let rate = *to_rate / *from_rate;
9595+ let rounded_rate = round_to_sig_figs(rate, 6);
9696+ Ok(rounded_rate)
8697}
87988899/// Fetch currency rates from the Frankfurter API (native version)