# base/format (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/base/format/

Formatting utilities. (the original base/format.js, Format in the original import.js)
- Gathers number string formatting that repeats in every game, such as currency and score display.
- The original takes JS numbers (f64). The Rust version also takes f64 and produces the same strings as the original for rounding, negatives, 0, infinity and NaN.
  toFixed rounds by the actual value and rounds exact halves up. toLocaleString rounds half up at the third decimal of the shortest decimal form.
  String(number) is the Number.prototype.toString form, so values of 1e21 or more and 1e-7 or less are written in exponent form. (1e+21, 1e-7)
- Rust has no default arguments, so they are always passed. (the original defaults: format_number's locale is "en-US", format_number_with_unit's is "ko-KR",
  format_compact_number's fraction_digits is 1, format_padded_number's range is f64::NEG_INFINITY and f64::INFINITY)
- Locales: the original leaves this to the browser's Intl (ICU). Rust std has nothing like it, so the decimal point, thousands separator, negative prefix, digit shapes,
  upper group size (Indian style is 3 then 2), minimum grouping digits (es, pl and others that do not group 1234) and NaN string were extracted from node 25's Intl (ICU 78.3, CLDR 48) into a table.
  Infinity is ∞ in every locale. Language tags are case-insensitive and are looked up in the table while removing trailing subtags one at a time. (zh-Hant-TW → zh-hant)
  Unicode extensions (-u-...) are not used to choose the number format. Tags not in the table use the system language, just as the original uses the browser's default locale.
  The system language is the first of the shared function also used by Localization.detect_language (localization::read_preferred_language_tags).
  (navigator.languages on the web; on desktop, the system preferred language order read by sys-locale: GetUserPreferredUILanguages on Windows, CFLocaleCopyPreferredLanguages on Mac,
  LANGUAGE / LC_ALL / LC_MESSAGES / LANG on Linux. If that is not in the table either, en-US)
- Language tag check: the original toLocaleString throws a RangeError for a tag that is not in BCP 47 form (Unicode locale identifier, UTS 35).
  The Rust version runs the same check as Chrome (V8's CanonicalizeLanguageTag, ECMA-402 IsStructurallyValidLanguageTag), and an invalid tag is Err(FormatError::InvalidLanguageTag).
  (an underscore "EN_gb", an empty string, a 4-letter language "root", duplicate variants or extension singletons, an empty extension "en-u" and so on. The error text matches Chrome's "Invalid language tag: ..." too)
- fraction_digits is valid from 0 ~ 100 like the original toFixed. Going beyond does not throw and outputs that many digits.

Example: Display scores, currency and time

```rust
use vanilla::format;

assert_eq!(format::format_number(12480.0, "en-US").unwrap(), "12,480");
assert_eq!(format::format_number_with_unit(1200000.0, " G", "ko-KR").unwrap(), "1,200,000 G");
assert_eq!(format::format_compact_number(5600000.0, 1), "5.6M");
assert_eq!(format::format_padded_number(7.0, 3, 0.0, 999.0), "007");
assert_eq!(format::format_minutes_seconds(75.0), "1:15");
```

## Functions and constants

- `pub fn format_number(value: f64, locale: &str) -> Result<String, FormatError>` (method, since 0.3.2): Returns with thousands separators. (12480 -> "12,480", the original default locale is "en-US")
  - `value` f64: Number to display.
  - `locale` &str: Language tag. (like "en-US", "ko-KR", case-insensitive. If not in the table, the system language is used, and en-US if that is not in the table either)
  - returns Result<String, FormatError>: Locale formatted text. (decimals are rounded half up to 0 ~ 3 digits and trailing zeros are dropped. NaN is the locale's NaN text, infinity is ∞)
Err(FormatError::InvalidLanguageTag) if the language tag is not in BCP 47 form, like the original RangeError. (an underscore "en_US", an empty string and so on)

  Example: Decimal point and grouping symbols that differ by locale

  ```rust
  use vanilla::format;
  
  assert_eq!(format::format_number(1234.5678, "en-US").unwrap(), "1,234.568");
  assert_eq!(format::format_number(1234567.891, "de-DE").unwrap(), "1.234.567,891");
  assert_eq!(format::format_number(123456789.123, "hi-IN").unwrap(), "12,34,56,789.123");
  assert_eq!(format::format_number(-0.0001, "en-US").unwrap(), "-0");
  assert!(format::format_number(1234.5, "en_US").is_err());
  ```

- `pub fn format_number_with_unit(value: f64, unit_suffix: &str, locale: &str) -> Result<String, FormatError>` (method, since 0.4.0): Thousands separators + unit suffix. (1200000, "won" -> "1,200,000won", the original default locale is "ko-KR")
  - `value` f64: Number to display.
  - `unit_suffix` &str: Unit string appended at the end. (no space in between)
  - `locale` &str: Language tag. (same as format_number)
  - returns Result<String, FormatError>: The format_number text with unit_suffix appended. Err(FormatError::InvalidLanguageTag) for an invalid language tag, like format_number.

  Example: Gold and point units

  ```rust
  use vanilla::format;
  
  assert_eq!(format::format_number_with_unit(1200000.0, " G", "ko-KR").unwrap(), "1,200,000 G");
  assert_eq!(format::format_number_with_unit(-5.0, "pt", "en-US").unwrap(), "-5pt");
  ```

- `pub fn format_compact_number(value: f64, fraction_digits: usize) -> String` (method, since 0.4.0): Returns a large number shortened. (1234 -> "1.2K", 5600000 -> "5.6M", the original default fractionDigits is 1)
  - If the rounded text becomes 1000, it moves up to the next unit like Intl compact notation. (999999 -> "1M")
  - `value` f64: Number to display. (negatives shorten the absolute value and prepend -)
  - `fraction_digits` usize: Number of decimal digits of the shortened number. (trailing zeros removed, not used if the absolute value is under 1000)
  - returns String: A string shortened with K if the absolute value is 1000 or more, M if 1000000 or more, B if 1000000000 or more. Under 1000 it stays in String(number) form.
(rounding is in toFixed form, and if rounding gives 1000 it moves up to the next unit, so 999999 is "1M", NaN is "NaN")

  Example: Unit boundaries and rounding

  ```rust
  use vanilla::format;
  
  assert_eq!(format::format_compact_number(1234.0, 1), "1.2K");
  assert_eq!(format::format_compact_number(1234567890.0, 2), "1.23B");
  assert_eq!(format::format_compact_number(-1234.0, 1), "-1.2K");
  assert_eq!(format::format_compact_number(999.5, 1), "999.5");
  assert_eq!(format::format_compact_number(999999.0, 1), "1M");
  ```

- `pub fn format_padded_number(value: f64, digit_count: usize, minimum_value: f64, maximum_value: f64) -> String` (method, since 0.4.0): Returns the value clamped to a range and zero-padded to a digit count. (7-segment counter display and such)
  - format_padded_number(7.0, 3, ..) -> "007", format_padded_number(-5.0, 3, ..) -> "-05"
  - The original default range is minimum_value = f64::NEG_INFINITY, maximum_value = f64::INFINITY
  - `value` f64: Number to display.
  - `digit_count` usize: Total number of digits. (for negatives the - sign counts as one digit)
  - `minimum_value` f64: Lower bound. (f64::NEG_INFINITY for no bound)
  - `maximum_value` f64: Upper bound. (f64::INFINITY for no bound)
  - returns String: String clamped to the range and zero-padded at the front. (not cut if longer than the digit count. Decimals, NaN and exponent forms pad the String(number) string as is; NaN if the value or a bound is NaN)

  Example: Three-digit counter

  ```rust
  use vanilla::format;
  
  assert_eq!(format::format_padded_number(7.0, 3, f64::NEG_INFINITY, f64::INFINITY), "007");
  assert_eq!(format::format_padded_number(-5.0, 3, f64::NEG_INFINITY, f64::INFINITY), "-05");
  assert_eq!(format::format_padded_number(1234.0, 3, -99.0, 999.0), "999");
  assert_eq!(format::format_padded_number(-1234.0, 3, -99.0, 999.0), "-99");
  ```

- `pub fn format_minutes_seconds(total_seconds: f64) -> String` (method, since 0.4.0): Returns seconds as "min:sec". (75 -> "1:15")
  - `total_seconds` f64: Total time. (seconds, decimals are dropped and negatives count as 0)
  - returns String: "minutes:seconds" string. (seconds are two digits, minutes stay as is even past 60. NaN is "NaN:NaN")

## FormatError (enum) (Clone, Debug, PartialEq, Eq, std::fmt::Display, std::error::Error)

Formatting error. (where the original throws a RangeError)

Example: Invalid language tag

```rust
use vanilla::format::{self, FormatError};

let error = format::format_number(1234.5, "EN_gb").unwrap_err();
assert_eq!(error, FormatError::InvalidLanguageTag(String::from("EN_gb")));
assert_eq!(error.to_string(), "Invalid language tag: EN_gb");
```

- `InvalidLanguageTag` = `InvalidLanguageTag(String)`: The language tag is not in BCP 47 form (Unicode locale identifier). (the tag text of the original RangeError "Invalid language tag: ...")
- The tag text is the same as what Chrome prints in the error: as given if the leading language identifier part is wrong, lowercased if a later extension or duplicate is wrong.
