| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
use core::fmt::Display; |
| 6 |
|
| 7 |
use crate::Cow; |
| 8 |
use crate::input::Decimal; |
| 9 |
use crate::{ |
| 10 |
DecimalFormatter, |
| 11 |
error::CompactExponentError, |
| 12 |
options::CompactDecimalFormatterOptions, |
| 13 |
preferences::{CompactDecimalFormatterPreferences, DecimalFormatterPreferences}, |
| 14 |
provider::*, |
| 15 |
}; |
| 16 |
#[cfg(feature = "alloc")] |
| 17 |
use alloc::string::String; |
| 18 |
use fixed_decimal::UnsignedDecimal; |
| 19 |
use icu_pattern::{Pattern, SinglePlaceholder}; |
| 20 |
use icu_plurals::{PluralOperands, PluralRules}; |
| 21 |
use icu_provider::DataError; |
| 22 |
use icu_provider::{marker::ErasedMarker, prelude::*}; |
| 23 |
use writeable::Writeable; |
| 24 |
|
| 25 |
/// A formatter that renders locale-sensitive compact numbers. |
| 26 |
/// |
| 27 |
/// <div class="stab unstable"> |
| 28 |
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways, |
| 29 |
/// including in SemVer minor releases. Do not use this type unless you are prepared for things to occasionally break. |
| 30 |
/// |
| 31 |
/// Graduation tracking issue: [issue #7161](https://github.com/unicode-org/icu4x/issues/7161). |
| 32 |
/// </div> |
| 33 |
/// |
| 34 |
/// ✨ *Enabled with the `unstable` Cargo feature.* |
| 35 |
/// |
| 36 |
/// # Examples |
| 37 |
/// |
| 38 |
/// ``` |
| 39 |
/// use icu::decimal::CompactDecimalFormatter; |
| 40 |
/// use icu::locale::locale; |
| 41 |
/// use writeable::assert_writeable_eq; |
| 42 |
/// |
| 43 |
/// let short_french = CompactDecimalFormatter::try_new_short( |
| 44 |
/// locale!("fr").into(), |
| 45 |
/// Default::default(), |
| 46 |
/// ) |
| 47 |
/// .unwrap(); |
| 48 |
/// |
| 49 |
/// let [long_french, long_japanese, long_bangla] = |
| 50 |
/// [locale!("fr"), locale!("ja"), locale!("bn")].map(|locale| { |
| 51 |
/// CompactDecimalFormatter::try_new_long( |
| 52 |
/// locale.into(), |
| 53 |
/// Default::default(), |
| 54 |
/// ) |
| 55 |
/// .unwrap() |
| 56 |
/// }); |
| 57 |
/// |
| 58 |
/// /// Supports short and long notations: |
| 59 |
/// # // The following line contains U+00A0 NO-BREAK SPACE. |
| 60 |
/// assert_writeable_eq!(short_french.format(&35_357_670i64.into()), "35 M"); |
| 61 |
/// assert_writeable_eq!( |
| 62 |
/// long_french.format(&35_357_670i64.into()), |
| 63 |
/// "35 millions" |
| 64 |
/// ); |
| 65 |
/// /// The powers of ten used are locale-dependent: |
| 66 |
/// assert_writeable_eq!(long_japanese.format(&3535_7670i64.into()), "3536万"); |
| 67 |
/// /// So are the digits: |
| 68 |
/// assert_writeable_eq!( |
| 69 |
/// long_bangla.format(&3_53_57_670i64.into()), |
| 70 |
/// "৩.৫ কোটি" |
| 71 |
/// ); |
| 72 |
/// |
| 73 |
/// /// The output does not always contain digits: |
| 74 |
/// assert_writeable_eq!(long_french.format(&1000i64.into()), "mille"); |
| 75 |
/// ``` |
| 76 |
#[derive(Debug)] |
| 77 |
pub struct CompactDecimalFormatter { |
| 78 |
plural_rules: PluralRules, |
| 79 |
pub(crate) decimal_formatter: DecimalFormatter, |
| 80 |
compact_data: |
| 81 |
DataPayload<ErasedMarker<<DecimalCompactLongV1 as DynamicDataMarker>::DataStruct>>, |
| 82 |
} |
| 83 |
|
| 84 |
impl CompactDecimalFormatter { |
| 85 |
/// Creates a new short [`CompactDecimalFormatter`] from compiled data and an options bag. |
| 86 |
/// |
| 87 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 88 |
/// |
| 89 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 90 |
/// |
| 91 |
/// # Examples |
| 92 |
/// |
| 93 |
/// ``` |
| 94 |
/// use icu::decimal::CompactDecimalFormatter; |
| 95 |
/// use icu::locale::locale; |
| 96 |
/// use writeable::assert_writeable_eq; |
| 97 |
/// |
| 98 |
/// let formatter = CompactDecimalFormatter::try_new_short( |
| 99 |
/// locale!("sv").into(), |
| 100 |
/// Default::default(), |
| 101 |
/// ) |
| 102 |
/// .unwrap(); |
| 103 |
/// |
| 104 |
/// assert_writeable_eq!(formatter.format(&1234.into()), "1,2 tn"); |
| 105 |
/// ``` |
| 106 |
#[cfg(feature = "compiled_data")] |
| 107 |
pub fn try_new_short( |
| 108 |
prefs: CompactDecimalFormatterPreferences, |
| 109 |
options: CompactDecimalFormatterOptions, |
| 110 |
) -> Result<Self, DataError> { |
| 111 |
let locale = DecimalCompactShortV1::make_locale(prefs.locale_preferences); |
| 112 |
Ok(Self { |
| 113 |
decimal_formatter: DecimalFormatter::try_new((&prefs).into(), options.into())?, |
| 114 |
plural_rules: PluralRules::try_new_cardinal((&prefs).into())?, |
| 115 |
compact_data: load_with_fallback::<DecimalCompactShortV1>( |
| 116 |
&Baked, |
| 117 |
DecimalFormatterPreferences::from(&prefs) |
| 118 |
.nu_id(&locale) |
| 119 |
.into_iter() |
| 120 |
.chain([DataIdentifierBorrowed::for_locale(&locale)]), |
| 121 |
)? |
| 122 |
.payload |
| 123 |
.cast(), |
| 124 |
}) |
| 125 |
} |
| 126 |
|
| 127 |
icu_provider::gen_buffer_data_constructors!( |
| 128 |
(prefs: CompactDecimalFormatterPreferences, options: CompactDecimalFormatterOptions) -> error: DataError, |
| 129 |
functions: [ |
| 130 |
try_new_short: skip, |
| 131 |
try_new_short_with_buffer_provider, |
| 132 |
try_new_short_unstable, |
| 133 |
Self, |
| 134 |
] |
| 135 |
); |
| 136 |
|
| 137 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_short)] |
| 138 |
pub fn try_new_short_unstable<D>( |
| 139 |
provider: &D, |
| 140 |
prefs: CompactDecimalFormatterPreferences, |
| 141 |
options: CompactDecimalFormatterOptions, |
| 142 |
) -> Result<Self, DataError> |
| 143 |
where |
| 144 |
D: DataProvider<DecimalCompactShortV1> |
| 145 |
+ DataProvider<DecimalSymbolsV1> |
| 146 |
+ DataProvider<DecimalDigitsV1> |
| 147 |
+ DataProvider<icu_plurals::provider::PluralsCardinalV1> |
| 148 |
+ ?Sized, |
| 149 |
{ |
| 150 |
let locale = DecimalCompactShortV1::make_locale(prefs.locale_preferences); |
| 151 |
Ok(Self { |
| 152 |
decimal_formatter: DecimalFormatter::try_new_unstable( |
| 153 |
provider, |
| 154 |
(&prefs).into(), |
| 155 |
options.into(), |
| 156 |
)?, |
| 157 |
plural_rules: PluralRules::try_new_cardinal_unstable(provider, (&prefs).into())?, |
| 158 |
compact_data: load_with_fallback::<DecimalCompactShortV1>( |
| 159 |
provider, |
| 160 |
DecimalFormatterPreferences::from(&prefs) |
| 161 |
.nu_id(&locale) |
| 162 |
.into_iter() |
| 163 |
.chain([DataIdentifierBorrowed::for_locale(&locale)]), |
| 164 |
)? |
| 165 |
.payload |
| 166 |
.cast(), |
| 167 |
}) |
| 168 |
} |
| 169 |
|
| 170 |
/// Creates a new long [`CompactDecimalFormatter`] from compiled data and an options bag. |
| 171 |
/// |
| 172 |
/// ✨ *Enabled with the `compiled_data` Cargo feature.* |
| 173 |
/// |
| 174 |
/// [📚 Help choosing a constructor](icu_provider::constructors) |
| 175 |
/// |
| 176 |
/// # Examples |
| 177 |
/// |
| 178 |
/// ``` |
| 179 |
/// use icu::decimal::CompactDecimalFormatter; |
| 180 |
/// use icu::locale::locale; |
| 181 |
/// use writeable::assert_writeable_eq; |
| 182 |
/// |
| 183 |
/// let formatter = CompactDecimalFormatter::try_new_long( |
| 184 |
/// locale!("sv").into(), |
| 185 |
/// Default::default(), |
| 186 |
/// ) |
| 187 |
/// .unwrap(); |
| 188 |
/// |
| 189 |
/// assert_writeable_eq!(formatter.format(&1234.into()), "1,2 tusen"); |
| 190 |
/// ``` |
| 191 |
#[cfg(feature = "compiled_data")] |
| 192 |
pub fn try_new_long( |
| 193 |
prefs: CompactDecimalFormatterPreferences, |
| 194 |
options: CompactDecimalFormatterOptions, |
| 195 |
) -> Result<Self, DataError> { |
| 196 |
let locale = DecimalCompactLongV1::make_locale(prefs.locale_preferences); |
| 197 |
Ok(Self { |
| 198 |
decimal_formatter: DecimalFormatter::try_new((&prefs).into(), options.into())?, |
| 199 |
plural_rules: PluralRules::try_new_cardinal((&prefs).into())?, |
| 200 |
compact_data: load_with_fallback::<DecimalCompactLongV1>( |
| 201 |
&Baked, |
| 202 |
DecimalFormatterPreferences::from(&prefs) |
| 203 |
.nu_id(&locale) |
| 204 |
.into_iter() |
| 205 |
.chain([DataIdentifierBorrowed::for_locale(&locale)]), |
| 206 |
)? |
| 207 |
.payload |
| 208 |
.cast(), |
| 209 |
}) |
| 210 |
} |
| 211 |
|
| 212 |
icu_provider::gen_buffer_data_constructors!( |
| 213 |
(prefs: CompactDecimalFormatterPreferences, options: CompactDecimalFormatterOptions) -> error: DataError, |
| 214 |
functions: [ |
| 215 |
try_new_long: skip, |
| 216 |
try_new_long_with_buffer_provider, |
| 217 |
try_new_long_unstable, |
| 218 |
Self, |
| 219 |
] |
| 220 |
); |
| 221 |
|
| 222 |
#[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_long)] |
| 223 |
pub fn try_new_long_unstable<D>( |
| 224 |
provider: &D, |
| 225 |
prefs: CompactDecimalFormatterPreferences, |
| 226 |
options: CompactDecimalFormatterOptions, |
| 227 |
) -> Result<Self, DataError> |
| 228 |
where |
| 229 |
D: DataProvider<DecimalCompactLongV1> |
| 230 |
+ DataProvider<DecimalSymbolsV1> |
| 231 |
+ DataProvider<DecimalDigitsV1> |
| 232 |
+ DataProvider<icu_plurals::provider::PluralsCardinalV1> |
| 233 |
+ ?Sized, |
| 234 |
{ |
| 235 |
let locale = DecimalCompactLongV1::make_locale(prefs.locale_preferences); |
| 236 |
Ok(Self { |
| 237 |
decimal_formatter: DecimalFormatter::try_new_unstable( |
| 238 |
provider, |
| 239 |
(&prefs).into(), |
| 240 |
options.into(), |
| 241 |
)?, |
| 242 |
plural_rules: PluralRules::try_new_cardinal_unstable(provider, (&prefs).into())?, |
| 243 |
compact_data: load_with_fallback::<DecimalCompactLongV1>( |
| 244 |
provider, |
| 245 |
DecimalFormatterPreferences::from(&prefs) |
| 246 |
.nu_id(&locale) |
| 247 |
.into_iter() |
| 248 |
.chain([DataIdentifierBorrowed::for_locale(&locale)]), |
| 249 |
)? |
| 250 |
.payload |
| 251 |
.cast(), |
| 252 |
}) |
| 253 |
} |
| 254 |
|
| 255 |
/// Formats a [`Decimal`] by automatically scaling and rounding it. |
| 256 |
/// |
| 257 |
/// The result may have a fractional digit only if it is compact and its |
| 258 |
/// significand is less than 10. Trailing fractional 0s are omitted. |
| 259 |
/// |
| 260 |
/// # Examples |
| 261 |
/// |
| 262 |
/// ``` |
| 263 |
/// use icu::decimal::CompactDecimalFormatter; |
| 264 |
/// use icu::decimal::input::{Decimal, SignDisplay}; |
| 265 |
/// use icu::locale::locale; |
| 266 |
/// use writeable::assert_writeable_eq; |
| 267 |
/// |
| 268 |
/// let short_english = CompactDecimalFormatter::try_new_short( |
| 269 |
/// locale!("en").into(), |
| 270 |
/// Default::default(), |
| 271 |
/// ) |
| 272 |
/// .unwrap(); |
| 273 |
/// |
| 274 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(0)), "0"); |
| 275 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(2)), "2"); |
| 276 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(843)), "843"); |
| 277 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(2207)), "2.2K"); |
| 278 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(15127)), "15K"); |
| 279 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(3010349)), "3M"); |
| 280 |
/// assert_writeable_eq!(short_english.format(&Decimal::from(-13132)), "-13K"); |
| 281 |
/// |
| 282 |
/// // The sign display on the Decimal is respected: |
| 283 |
/// assert_writeable_eq!( |
| 284 |
/// short_english.format( |
| 285 |
/// &Decimal::from(2500).with_sign_display(SignDisplay::ExceptZero) |
| 286 |
/// ), |
| 287 |
/// "+2.5K" |
| 288 |
/// ); |
| 289 |
/// ``` |
| 290 |
/// |
| 291 |
/// The result is the nearest such compact number, with halfway cases- |
| 292 |
/// rounded towards the number with an even least significant digit. |
| 293 |
/// |
| 294 |
/// ``` |
| 295 |
/// # use icu::decimal::CompactDecimalFormatter; |
| 296 |
/// # use icu::locale::locale; |
| 297 |
/// # use writeable::assert_writeable_eq; |
| 298 |
/// # |
| 299 |
/// # let short_english = CompactDecimalFormatter::try_new_short( |
| 300 |
/// # locale!("en").into(), |
| 301 |
/// # Default::default(), |
| 302 |
/// # ).unwrap(); |
| 303 |
/// assert_writeable_eq!( |
| 304 |
/// short_english.format(&"999499.99".parse().unwrap()), |
| 305 |
/// "999K" |
| 306 |
/// ); |
| 307 |
/// assert_writeable_eq!( |
| 308 |
/// short_english.format(&"999500.00".parse().unwrap()), |
| 309 |
/// "1M" |
| 310 |
/// ); |
| 311 |
/// assert_writeable_eq!( |
| 312 |
/// short_english.format(&"1650".parse().unwrap()), |
| 313 |
/// "1.6K" |
| 314 |
/// ); |
| 315 |
/// assert_writeable_eq!( |
| 316 |
/// short_english.format(&"1750".parse().unwrap()), |
| 317 |
/// "1.8K" |
| 318 |
/// ); |
| 319 |
/// assert_writeable_eq!(short_english.format(&"1950".parse().unwrap()), "2K"); |
| 320 |
/// assert_writeable_eq!( |
| 321 |
/// short_english.format(&"-1172700".parse().unwrap()), |
| 322 |
/// "-1.2M" |
| 323 |
/// ); |
| 324 |
/// assert_writeable_eq!( |
| 325 |
/// short_english.format(&"0.2222".parse().unwrap()), |
| 326 |
/// "0.22" |
| 327 |
/// ); |
| 328 |
/// ``` |
| 329 |
/// |
| 330 |
/// Floating point inputs should use [`FloatPrecision::RoundTrip`](fixed_decimal::FloatPrecision::RoundTrip). |
| 331 |
/// |
| 332 |
/// ``` |
| 333 |
/// # use icu::decimal::input::{Decimal, FloatPrecision}; |
| 334 |
/// # use icu::decimal::CompactDecimalFormatter; |
| 335 |
/// # use icu::locale::locale; |
| 336 |
/// # use writeable::assert_writeable_eq; |
| 337 |
/// # |
| 338 |
/// # let short_english = CompactDecimalFormatter::try_new_short( |
| 339 |
/// # locale!("en").into(), |
| 340 |
/// # Default::default(), |
| 341 |
/// # ).unwrap(); |
| 342 |
/// assert_writeable_eq!( |
| 343 |
/// short_english.format( |
| 344 |
/// &Decimal::try_from_f64(999_499.99, FloatPrecision::RoundTrip) |
| 345 |
/// .unwrap() |
| 346 |
/// ), |
| 347 |
/// "999K" |
| 348 |
/// ); |
| 349 |
/// ``` |
| 350 |
pub fn format<'a>(&'a self, value: &Decimal) -> impl Writeable + Display + 'a { |
| 351 |
self.decimal_formatter |
| 352 |
.format_sign(value.sign, self.format_unsigned(&value.absolute)) |
| 353 |
} |
| 354 |
|
| 355 |
pub(crate) fn format_unsigned<'a>( |
| 356 |
&'a self, |
| 357 |
value: &UnsignedDecimal, |
| 358 |
) -> FormattedUnsignedCompactDecimal<'a> { |
| 359 |
let log10_type = value.nonzero_magnitude_start(); |
| 360 |
|
| 361 |
let entry = self |
| 362 |
.compact_data |
| 363 |
.get() |
| 364 |
.0 |
| 365 |
.iter() |
| 366 |
.enumerate() |
| 367 |
.filter(|&(_, t)| i16::from(t.sized) <= log10_type) |
| 368 |
.last(); |
| 369 |
|
| 370 |
let exponent = entry |
| 371 |
.map(|(_, t)| t.sized - t.variable.get_default().0.get()) |
| 372 |
.unwrap_or_default(); |
| 373 |
let rounding_magnitude = if log10_type > i16::from(exponent) { |
| 374 |
// If we have at least 2 digits before the decimal point, |
| 375 |
// round to eliminate the fractional part. |
| 376 |
i16::from(exponent) |
| 377 |
} else { |
| 378 |
// …otherwise, round to two significant digits |
| 379 |
log10_type - 1 |
| 380 |
}; |
| 381 |
if let Some(t) = self |
| 382 |
.compact_data |
| 383 |
.get() |
| 384 |
.0 |
| 385 |
.get(entry.map(|(idx, _)| idx + 1).unwrap_or_default()) |
| 386 |
{ |
| 387 |
let next_exponent = t.sized - t.variable.get_default().0.get(); |
| 388 |
|
| 389 |
let rounds_to_next_exponent = log10_type + 1 == i16::from(next_exponent) |
| 390 |
&& value.digit_at(rounding_magnitude - 1) >= 5 |
| 391 |
&& (rounding_magnitude..=log10_type).all(|m| value.digit_at(m) == 9); |
| 392 |
|
| 393 |
// We got bumped up a magnitude by rounding. |
| 394 |
if rounds_to_next_exponent { |
| 395 |
return FormattedUnsignedCompactDecimal { |
| 396 |
pattern: Some(t.variable.get(1.into(), &self.plural_rules).1), |
| 397 |
significand: UnsignedDecimal::ONE, |
| 398 |
decimal_formatter: &self.decimal_formatter, |
| 399 |
exponent: next_exponent, |
| 400 |
}; |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
FormattedUnsignedCompactDecimal { |
| 405 |
pattern: entry.map(|(_, t)| { |
| 406 |
t.variable |
| 407 |
.get( |
| 408 |
(&value |
| 409 |
.clone() |
| 410 |
.rounded(rounding_magnitude) |
| 411 |
.multiplied_pow10(-i16::from(exponent)) |
| 412 |
.trimmed_end()) |
| 413 |
.into(), |
| 414 |
&self.plural_rules, |
| 415 |
) |
| 416 |
.1 |
| 417 |
}), |
| 418 |
significand: value |
| 419 |
.clone() |
| 420 |
.rounded(rounding_magnitude) |
| 421 |
.multiplied_pow10(-i16::from(exponent)) |
| 422 |
.trimmed_end(), |
| 423 |
decimal_formatter: &self.decimal_formatter, |
| 424 |
exponent, |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
/// Formats a [`Decimal`], returning a [`String`]. |
| 429 |
/// |
| 430 |
/// ✨ *Enabled with the `alloc` Cargo feature.* |
| 431 |
#[cfg(feature = "alloc")] |
| 432 |
pub fn format_to_string(&self, value: &Decimal) -> String { |
| 433 |
use writeable::Writeable; |
| 434 |
self.format(value).write_to_string().into_owned() |
| 435 |
} |
| 436 |
|
| 437 |
/// Formats a [`Decimal`] with a given exponent according to locale data. |
| 438 |
/// |
| 439 |
/// This is an advanced API; prefer using [`Self::format()`] in simple |
| 440 |
/// cases. |
| 441 |
/// |
| 442 |
/// Since the caller specifies the exact digits that are displayed, this |
| 443 |
/// allows for arbitrarily complex rounding rules. |
| 444 |
/// However, contrary to [`DecimalFormatter::format()`], this operation |
| 445 |
/// can fail, because the given exponent can be inconsistent with |
| 446 |
/// the locale data; for instance, if the locale uses lakhs and crores and |
| 447 |
/// millions are requested, or vice versa, this function returns an error. |
| 448 |
/// |
| 449 |
/// The given exponent should be constructed using |
| 450 |
/// [`Self::compact_exponent_for_magnitude()`] on the same |
| 451 |
/// [`CompactDecimalFormatter`] object. |
| 452 |
/// Specifically, `formatter.format_with_exponent(s, e)` requires that `e` |
| 453 |
/// be equal to `formatter.compact_exponent_for_magnitude(s.nonzero_magnitude_start() + e)`. |
| 454 |
/// |
| 455 |
/// # Examples |
| 456 |
/// |
| 457 |
/// ``` |
| 458 |
/// # use icu::decimal::{CompactDecimalFormatter, input::Decimal}; |
| 459 |
/// # use icu::locale::locale; |
| 460 |
/// # use writeable::assert_writeable_eq; |
| 461 |
/// # use std::str::FromStr; |
| 462 |
/// # |
| 463 |
/// # let short_french = CompactDecimalFormatter::try_new_short( |
| 464 |
/// # locale!("fr").into(), |
| 465 |
/// # Default::default(), |
| 466 |
/// # ).unwrap(); |
| 467 |
/// # let long_french = CompactDecimalFormatter::try_new_long( |
| 468 |
/// # locale!("fr").into(), |
| 469 |
/// # Default::default() |
| 470 |
/// # ).unwrap(); |
| 471 |
/// # let long_bangla = CompactDecimalFormatter::try_new_long( |
| 472 |
/// # locale!("bn").into(), |
| 473 |
/// # Default::default() |
| 474 |
/// # ).unwrap(); |
| 475 |
/// # |
| 476 |
/// let one_point_two = Decimal::from_str("1.20").unwrap(); |
| 477 |
/// let three = Decimal::from_str("+3").unwrap(); |
| 478 |
/// let ten = 10.into(); |
| 479 |
/// # // The following line contains U+00A0 NO-BREAK SPACE. |
| 480 |
/// assert_writeable_eq!( |
| 481 |
/// short_french |
| 482 |
/// .format_with_exponent(&one_point_two, 6) |
| 483 |
/// .unwrap(), |
| 484 |
/// "1,20 M" |
| 485 |
/// ); |
| 486 |
/// assert_writeable_eq!( |
| 487 |
/// long_french.format_with_exponent(&one_point_two, 6).unwrap(), |
| 488 |
/// "1,20 million" |
| 489 |
/// ); |
| 490 |
/// |
| 491 |
/// # // The following line contains U+00A0 NO-BREAK SPACE. |
| 492 |
/// assert_writeable_eq!( |
| 493 |
/// short_french.format_with_exponent(&three, 6).unwrap(), |
| 494 |
/// "+3 M" |
| 495 |
/// ); |
| 496 |
/// assert_writeable_eq!( |
| 497 |
/// long_french.format_with_exponent(&three, 6).unwrap(), |
| 498 |
/// "+3 millions" |
| 499 |
/// ); |
| 500 |
/// |
| 501 |
/// assert_writeable_eq!( |
| 502 |
/// long_bangla.format_with_exponent(&ten, 5).unwrap(), |
| 503 |
/// "১০ লাখ" |
| 504 |
/// ); |
| 505 |
/// |
| 506 |
/// assert_eq!( |
| 507 |
/// long_bangla |
| 508 |
/// .format_with_exponent(&one_point_two, 6) |
| 509 |
/// .err() |
| 510 |
/// .unwrap() |
| 511 |
/// .to_string(), |
| 512 |
/// "Expected compact exponent 5 for 10^6, got 6", |
| 513 |
/// ); |
| 514 |
/// assert_eq!( |
| 515 |
/// long_french |
| 516 |
/// .format_with_exponent(&ten, 5) |
| 517 |
/// .err() |
| 518 |
/// .unwrap() |
| 519 |
/// .to_string(), |
| 520 |
/// "Expected compact exponent 6 for 10^6, got 5", |
| 521 |
/// ); |
| 522 |
/// |
| 523 |
/// /// Some patterns omit the digits; in those cases, the output does not |
| 524 |
/// /// contain the sequence of digits specified by the significand. |
| 525 |
/// let one = 1.into(); |
| 526 |
/// assert_writeable_eq!( |
| 527 |
/// long_french.format_with_exponent(&one, 3).unwrap(), |
| 528 |
/// "mille" |
| 529 |
/// ); |
| 530 |
/// ``` |
| 531 |
pub fn format_with_exponent<'l>( |
| 532 |
&'l self, |
| 533 |
significand: &'l Decimal, |
| 534 |
exponent: u8, |
| 535 |
) -> Result<impl Writeable + Display + 'l, CompactExponentError> { |
| 536 |
let log10_type = significand.absolute.nonzero_magnitude_start() + i16::from(exponent); |
| 537 |
|
| 538 |
let (pattern, expected_exponent) = self |
| 539 |
.compact_data |
| 540 |
.get() |
| 541 |
.0 |
| 542 |
.iter() |
| 543 |
.filter(|&t| log10_type >= i16::from(t.sized)) |
| 544 |
.last() |
| 545 |
.map(|t| { |
| 546 |
( |
| 547 |
t.variable |
| 548 |
.get((&significand.absolute).into(), &self.plural_rules) |
| 549 |
.1, |
| 550 |
t.sized - t.variable.get_default().0.get(), |
| 551 |
) |
| 552 |
}) |
| 553 |
.unwrap_or((Pattern::<SinglePlaceholder>::PASS_THROUGH, 0)); |
| 554 |
|
| 555 |
if exponent != expected_exponent { |
| 556 |
return Err(CompactExponentError { |
| 557 |
actual: exponent, |
| 558 |
expected: expected_exponent, |
| 559 |
magnitude: log10_type, |
| 560 |
}); |
| 561 |
} |
| 562 |
|
| 563 |
Ok(self.decimal_formatter.format_sign( |
| 564 |
significand.sign, |
| 565 |
pattern.interpolate([self |
| 566 |
.decimal_formatter |
| 567 |
.format_unsigned(Cow::Borrowed(&significand.absolute))]), |
| 568 |
)) |
| 569 |
} |
| 570 |
|
| 571 |
/// Returns the compact decimal exponent that should be used for a number of |
| 572 |
/// the given magnitude when using this formatter. |
| 573 |
/// |
| 574 |
/// # Examples |
| 575 |
/// ``` |
| 576 |
/// use icu::decimal::CompactDecimalFormatter; |
| 577 |
/// use icu::locale::locale; |
| 578 |
/// |
| 579 |
/// let [long_french, long_japanese, long_bangla] = [ |
| 580 |
/// locale!("fr").into(), |
| 581 |
/// locale!("ja").into(), |
| 582 |
/// locale!("bn").into(), |
| 583 |
/// ] |
| 584 |
/// .map(|locale| { |
| 585 |
/// CompactDecimalFormatter::try_new_long(locale, Default::default()) |
| 586 |
/// .unwrap() |
| 587 |
/// }); |
| 588 |
/// /// French uses millions. |
| 589 |
/// assert_eq!(long_french.compact_exponent_for_magnitude(6), 6); |
| 590 |
/// /// Bangla uses lakhs. |
| 591 |
/// assert_eq!(long_bangla.compact_exponent_for_magnitude(6), 5); |
| 592 |
/// /// Japanese uses myriads. |
| 593 |
/// assert_eq!(long_japanese.compact_exponent_for_magnitude(6), 4); |
| 594 |
/// ``` |
| 595 |
pub fn compact_exponent_for_magnitude(&self, magnitude: i16) -> u8 { |
| 596 |
self.compact_data |
| 597 |
.get() |
| 598 |
.0 |
| 599 |
.iter() |
| 600 |
.filter(|t| magnitude >= i16::from(t.sized)) |
| 601 |
.last() |
| 602 |
.map(|t| t.sized - t.variable.get_default().0.get()) |
| 603 |
.unwrap_or_default() |
| 604 |
} |
| 605 |
} |
| 606 |
|
| 607 |
#[doc(hidden)] // TODO(#3647): should be private |
| 608 |
#[derive(Debug)] |
| 609 |
pub struct FormattedUnsignedCompactDecimal<'l> { |
| 610 |
pattern: Option<&'l Pattern<SinglePlaceholder>>, |
| 611 |
significand: UnsignedDecimal, |
| 612 |
decimal_formatter: &'l DecimalFormatter, |
| 613 |
exponent: u8, |
| 614 |
} |
| 615 |
|
| 616 |
impl Writeable for FormattedUnsignedCompactDecimal<'_> { |
| 617 |
fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result { |
| 618 |
self.pattern |
| 619 |
.unwrap_or(Pattern::<SinglePlaceholder>::PASS_THROUGH) |
| 620 |
.interpolate([self |
| 621 |
.decimal_formatter |
| 622 |
.format_unsigned(Cow::Borrowed(&self.significand))]) |
| 623 |
.write_to(sink) |
| 624 |
} |
| 625 |
} |
| 626 |
|
| 627 |
impl FormattedUnsignedCompactDecimal<'_> { |
| 628 |
pub(crate) fn plural_operands(&self) -> PluralOperands { |
| 629 |
PluralOperands::from_significand_and_exponent(&self.significand, self.exponent) |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
#[cfg(feature = "serde")] |
| 634 |
#[cfg(test)] |
| 635 |
mod tests { |
| 636 |
use super::*; |
| 637 |
use crate::options::GroupingStrategy; |
| 638 |
use icu_locale_core::locale; |
| 639 |
use icu_plurals::PluralElements; |
| 640 |
use writeable::assert_writeable_eq; |
| 641 |
|
| 642 |
#[allow(non_snake_case)] |
| 643 |
#[test] |
| 644 |
fn test_grouping() { |
| 645 |
// https://unicode-org.atlassian.net/browse/ICU-22254 |
| 646 |
#[derive(Debug)] |
| 647 |
struct TestCase<'a> { |
| 648 |
short: bool, |
| 649 |
options: CompactDecimalFormatterOptions, |
| 650 |
expected1T: &'a str, |
| 651 |
expected10T: &'a str, |
| 652 |
} |
| 653 |
let cases = [ |
| 654 |
TestCase { |
| 655 |
short: true, |
| 656 |
options: Default::default(), |
| 657 |
expected1T: "1000T", |
| 658 |
expected10T: "10,000T", |
| 659 |
}, |
| 660 |
TestCase { |
| 661 |
short: true, |
| 662 |
options: GroupingStrategy::Always.into(), |
| 663 |
expected1T: "1,000T", |
| 664 |
expected10T: "10,000T", |
| 665 |
}, |
| 666 |
TestCase { |
| 667 |
short: true, |
| 668 |
options: GroupingStrategy::Never.into(), |
| 669 |
expected1T: "1000T", |
| 670 |
expected10T: "10000T", |
| 671 |
}, |
| 672 |
TestCase { |
| 673 |
short: false, |
| 674 |
options: Default::default(), |
| 675 |
expected1T: "1000 trillion", |
| 676 |
expected10T: "10,000 trillion", |
| 677 |
}, |
| 678 |
TestCase { |
| 679 |
short: false, |
| 680 |
options: GroupingStrategy::Always.into(), |
| 681 |
expected1T: "1,000 trillion", |
| 682 |
expected10T: "10,000 trillion", |
| 683 |
}, |
| 684 |
TestCase { |
| 685 |
short: false, |
| 686 |
options: GroupingStrategy::Never.into(), |
| 687 |
expected1T: "1000 trillion", |
| 688 |
expected10T: "10000 trillion", |
| 689 |
}, |
| 690 |
]; |
| 691 |
for case in cases { |
| 692 |
let formatter = if case.short { |
| 693 |
CompactDecimalFormatter::try_new_short(locale!("en").into(), case.options.clone()) |
| 694 |
} else { |
| 695 |
CompactDecimalFormatter::try_new_long(locale!("en").into(), case.options.clone()) |
| 696 |
} |
| 697 |
.unwrap(); |
| 698 |
let result1T = formatter.format(&1_000_000_000_000_000i64.into()); |
| 699 |
assert_writeable_eq!(result1T, case.expected1T, "{:?}", case); |
| 700 |
let result10T = formatter.format(&10_000_000_000_000_000i64.into()); |
| 701 |
assert_writeable_eq!(result10T, case.expected10T, "{:?}", case); |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
#[test] |
| 706 |
fn plural() { |
| 707 |
let decimal = DecimalFormatter::try_new(locale!("fr").into(), Default::default()).unwrap(); |
| 708 |
let decimal = decimal.format_unsigned(Cow::Owned(999_999u64.into())); |
| 709 |
|
| 710 |
let compact = |
| 711 |
CompactDecimalFormatter::try_new_short(locale!("fr").into(), Default::default()) |
| 712 |
.unwrap(); |
| 713 |
let compact = compact.format_unsigned(&999_999u64.into()); |
| 714 |
|
| 715 |
let dollars = PluralElements::new("dollars US") |
| 716 |
.with_one_value(Some("dollar US")) |
| 717 |
.with_many_value(Some("de dollars US")); |
| 718 |
|
| 719 |
assert_eq!( |
| 720 |
*dollars.get( |
| 721 |
decimal.plural_operands(), |
| 722 |
&PluralRules::try_new(locale!("fr").into(), Default::default()).unwrap() |
| 723 |
), |
| 724 |
"dollars US" |
| 725 |
); |
| 726 |
|
| 727 |
assert_eq!( |
| 728 |
*dollars.get( |
| 729 |
compact.plural_operands(), |
| 730 |
&PluralRules::try_new(locale!("fr").into(), Default::default()).unwrap() |
| 731 |
), |
| 732 |
"de dollars US" |
| 733 |
); |
| 734 |
} |
| 735 |
|
| 736 |
#[test] |
| 737 |
fn regression_7387() { |
| 738 |
let formatter = |
| 739 |
CompactDecimalFormatter::try_new_short(locale!("ar").into(), Default::default()) |
| 740 |
.unwrap(); |
| 741 |
|
| 742 |
assert_writeable_eq!(formatter.format(&3_000_000i64.into()), "3\u{a0}مليون"); |
| 743 |
} |
| 744 |
|
| 745 |
#[test] |
| 746 |
fn numbering_system() { |
| 747 |
let default = |
| 748 |
CompactDecimalFormatter::try_new_short(locale!("lo").into(), Default::default()) |
| 749 |
.unwrap(); |
| 750 |
let lao = CompactDecimalFormatter::try_new_short( |
| 751 |
locale!("lo-u-nu-laoo").into(), |
| 752 |
Default::default(), |
| 753 |
) |
| 754 |
.unwrap(); |
| 755 |
|
| 756 |
// lo is one of the few locales that have different compact patterns per |
| 757 |
// numbering system (they differ by a NBSP) |
| 758 |
assert_writeable_eq!(default.format(&12345.into()), "12 ພັນ"); |
| 759 |
assert_writeable_eq!(lao.format(&12345.into()), "໑໒ພັນ"); |
| 760 |
} |
| 761 |
} |