use std::any::Any;
pub trait NumberFormatter {
fn format_double(&self, value: f64) -> String;
fn parse_double(&self, text: &str) -> Option<f64>;
}
pub trait ComparableNumberFormatter: NumberFormatter {
fn as_any(&self) -> &dyn Any;
fn same_as(&self, other: &dyn ComparableNumberFormatter) -> bool;
}
impl<F: NumberFormatter + PartialEq + 'static> ComparableNumberFormatter for F {
fn as_any(&self) -> &dyn Any {
self
}
fn same_as(&self, other: &dyn ComparableNumberFormatter) -> bool {
other.as_any().downcast_ref::<F>() == Some(self)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DecimalFormatter {
pub integer_digits: usize,
pub fraction_digits: usize,
}
impl Default for DecimalFormatter {
fn default() -> Self {
Self {
integer_digits: 1,
fraction_digits: 0,
}
}
}
impl NumberFormatter for DecimalFormatter {
fn format_double(&self, value: f64) -> String {
if value.is_nan() {
return "NaN".to_owned();
}
if value.is_infinite() {
return if value > 0.0 { "∞" } else { "-∞" }.to_owned();
}
let digits = value.abs().to_string();
let (integer, fraction) = digits.split_once('.').unwrap_or((&digits, ""));
let integer = integer.trim_start_matches('0');
let mut text = String::new();
if value < 0.0 {
text.push('-');
}
let integer_digits = if integer.is_empty() && fraction.is_empty() {
self.integer_digits.max(1)
} else {
self.integer_digits
};
text.extend(std::iter::repeat_n(
'0',
integer_digits.saturating_sub(integer.len()),
));
text.push_str(integer);
let padding = self.fraction_digits.saturating_sub(fraction.len());
if !fraction.is_empty() || padding > 0 {
text.push('.');
text.push_str(fraction);
text.extend(std::iter::repeat_n('0', padding));
}
text
}
fn parse_double(&self, text: &str) -> Option<f64> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let mut digits = 0;
let mut points = 0;
for character in unsigned.chars() {
match character {
'0'..='9' => digits += 1,
'.' => points += 1,
_ => return None,
}
}
if digits == 0 || points > 1 {
return None;
}
text.parse().ok()
}
}
const DISPLAY_SIGNIFICANT_DIGITS: usize = 10;
pub(super) fn round_for_display(value: f64) -> f64 {
round_to_significant_digits(value, DISPLAY_SIGNIFICANT_DIGITS)
}
fn round_to_significant_digits(value: f64, digits: usize) -> f64 {
if value == 0.0 || !value.is_finite() {
return value;
}
let one_more = format!("{value:.digits$e}");
let halfway = one_more
.split_once('e')
.is_some_and(|(mantissa, _)| mantissa.ends_with('5'))
&& one_more.parse::<f64>() == Ok(value);
let value = if halfway { value.next_up() } else { value };
let kept = digits - 1;
format!("{value:.kept$e}")
.parse()
.expect("Rust reads back the numbers it formats")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_formatter_writes_the_shortest_decimal_without_grouping() {
let formatter = DecimalFormatter::default();
assert_eq!(formatter.format_double(0.0), "0");
assert_eq!(formatter.format_double(-0.0), "0");
assert_eq!(formatter.format_double(3.0), "3");
assert_eq!(formatter.format_double(-12.5), "-12.5");
assert_eq!(formatter.format_double(1234567.0), "1234567");
assert_eq!(formatter.format_double(0.25), "0.25");
assert_eq!(formatter.format_double(1e-7), "0.0000001");
}
#[test]
fn integer_and_fraction_digits_pad_with_zeros() {
let formatter = DecimalFormatter {
integer_digits: 3,
fraction_digits: 2,
};
assert_eq!(formatter.format_double(5.0), "005.00");
assert_eq!(formatter.format_double(-0.125), "-000.125");
let bare = DecimalFormatter {
integer_digits: 0,
fraction_digits: 0,
};
assert_eq!(bare.format_double(0.5), ".5");
assert_eq!(bare.format_double(0.0), "0");
}
#[test]
fn parsing_takes_a_minus_digits_and_one_point() {
let formatter = DecimalFormatter::default();
assert_eq!(formatter.parse_double("42"), Some(42.0));
assert_eq!(formatter.parse_double("-3.5"), Some(-3.5));
assert_eq!(formatter.parse_double(".5"), Some(0.5));
assert_eq!(formatter.parse_double("5."), Some(5.0));
for text in [
"", "-", ".", "1.2.3", "1,000", "1e3", "+1", " 1", "abc", "inf", "NaN",
] {
assert_eq!(formatter.parse_double(text), None, "{text:?}");
}
}
#[test]
fn the_display_rounder_hides_floating_point_noise() {
assert_eq!(round_for_display(0.1 + 0.2), 0.3);
assert_eq!(round_for_display(1.0 / 3.0), 0.3333333333);
assert_eq!(round_for_display(12345678901234.0), 12345678900000.0);
assert_eq!(round_for_display(-2.0 / 3.0), -0.6666666667);
assert!(round_for_display(f64::NAN).is_nan());
assert_eq!(round_for_display(0.0), 0.0);
}
#[test]
fn a_halfway_value_rounds_toward_positive_infinity() {
assert_eq!(round_for_display(1234567890.5), 1234567891.0);
assert_eq!(round_for_display(-1234567890.5), -1234567890.0);
assert_eq!(round_for_display(1234567891.5), 1234567892.0);
}
}