From a9d29e65188ed7626fec0a393404e6e50f36b1f8 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Thu, 29 Feb 2024 22:59:54 -0500 Subject: [PATCH] Format numbers --- Cargo.lock | 2 ++ l10n/Cargo.toml | 1 + l10n/src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 39 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 23fd28f..3def0dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1143,6 +1143,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbc7fdec9d7f6671a3ebb3282c969962aba67c49f6abac5311959b65cafabc10" dependencies = [ "displaydoc", + "ryu", "smallvec", "writeable", ] @@ -2714,6 +2715,7 @@ version = "0.1.0" dependencies = [ "chrono", "chrono-tz", + "fixed_decimal", "fluent-ergonomics", "icu", "icu_locid", diff --git a/l10n/Cargo.toml b/l10n/Cargo.toml index 08382b2..a671860 100644 --- a/l10n/Cargo.toml +++ b/l10n/Cargo.toml @@ -8,6 +8,7 @@ edition = "2021" [dependencies] chrono = { version = "0.4" } chrono-tz = { version = "0.8" } +fixed_decimal = { version = "0.5.5", features = [ "ryu" ] } fluent-ergonomics = { path = "../fluent-ergonomics" } icu = { version = "1" } icu_locid = { version = "1" } diff --git a/l10n/src/lib.rs b/l10n/src/lib.rs index 4637268..e95ce9c 100644 --- a/l10n/src/lib.rs +++ b/l10n/src/lib.rs @@ -1,16 +1,18 @@ use std::ops::Deref; -use chrono::{Datelike, FixedOffset, NaiveDate, TimeZone, Timelike}; -use chrono_tz::{OffsetName, Tz}; +use chrono::{Datelike, NaiveDate, Timelike}; +use chrono_tz::{Tz}; +use fixed_decimal::{FixedDecimal}; use icu::{ datetime::options::length, - timezone::{CustomTimeZone, GmtOffset}, + decimal::{FixedDecimalFormatter}, }; -use icu_locid::{locale, Locale}; +use icu_locid::{Locale}; use icu_provider::DataLocale; -use std::str::FromStr; use sys_locale::get_locale; +pub use fixed_decimal::FloatPrecision; + #[derive(Clone, Debug)] pub struct L10N { locale: Locale, @@ -137,8 +139,15 @@ impl L10N { formatter.format_to_string(&icu_date.to_any()).unwrap() } - fn format_f64(&self, value: f64) -> String { - unimplemented!() + fn format_f64(&self, value: f64, precision: FloatPrecision) -> String { + let fdf = FixedDecimalFormatter::try_new( + &self.locale.clone().into(), + Default::default() + ).expect("locale should be present"); + + let number = FixedDecimal::try_from_f64(value, precision).unwrap(); + + fdf.format_to_string(&FixedDecimal::try_from_f64(value, precision).unwrap()) } } @@ -259,6 +268,25 @@ mod tests { #[test] fn it_formats_a_number_according_to_locale() { - unimplemented!() + let mut l10n = ref_l10n(); + + assert_eq!( + l10n.format_f64(100.4, FloatPrecision::Floating), + "100.4", + ); + assert_eq!( + l10n.format_f64(15000.4, FloatPrecision::Floating), + "15,000.4", + ); + + l10n.set_locale("de-DE".to_owned()); + assert_eq!( + l10n.format_f64(100.4, FloatPrecision::Floating), + "100,4", + ); + assert_eq!( + l10n.format_f64(15000.4, FloatPrecision::Floating), + "15.000,4", + ); } }