vanilladocs
vanillapunch.com
API / base/format

base/format

표기 유틸. (원본 base/format.js, 원본 import.js 의 Format)

  • 재화, 점수 표기처럼 어느 게임에서나 되풀이되는 숫자 글 만들기를 모았다.
  • 원본은 JS 의 수(f64)를 받는다. 러스트 판도 f64 를 받고, 반올림과 음수, 0, 무한대, NaN 의 글을 원본과 같게 낸다. toFixed 는 실제 값으로 반올림하고 딱 반이면 올린다. toLocaleString 은 가장 짧은 십진 표기에서 소수 셋째 자리로 반을 올린다. String(수)는 Number.prototype.toString 꼴이라 1e21 이상과 1e-7 이하는 지수로 쓴다. (1e+21, 1e-7)
  • 원본의 기본 인자는 러스트에 없어서 늘 넘긴다. (원본 기본값: format_number 의 locale 은 "en-US", format_number_with_unit 은 "ko-KR", format_compact_number 의 fraction_digits 는 1, format_padded_number 의 범위는 f64::NEG_INFINITY 와 f64::INFINITY)
  • 로캘: 원본은 브라우저의 Intl(ICU)에 맡긴다. 러스트 std 에는 그런 것이 없어서 소수점, 천 단위 기호, 음수 앞붙이, 숫자 모양, 위 묶음 길이(인도식은 3 다음 2), 최소 묶음 자리(1234 는 묶지 않는 es, pl 등), NaN 글을 node 25(ICU 78.3, CLDR 48)의 Intl 에서 뽑아 표로 넣었다. 무한대는 모든 로캘이 ∞ 다. 언어 태그는 대소문자를 가리지 않고 뒤 조각부터 하나씩 떼며 표에서 찾는다. (zh-Hant-TW → zh-hant) 유니코드 확장(-u-...)은 숫자 꼴을 고르는 데 보지 않는다. 표에 없는 태그는 원본이 브라우저의 기본 로캘로 쓰듯 시스템 언어로 쓴다. 시스템 언어는 Localization.detect_language 와 같은 공용 함수(localization::read_preferred_language_tags)의 첫째다. (웹은 navigator.languages, 데스크탑은 sys-locale 이 읽은 시스템 선호 언어 차례: 윈도우 GetUserPreferredUILanguages, 맥 CFLocaleCopyPreferredLanguages, 리눅스 LANGUAGE / LC_ALL / LC_MESSAGES / LANG. 그것도 표에 없으면 en-US)
  • 언어 태그 검사: 원본 toLocaleString 은 BCP 47(유니코드 로캘 식별자, UTS 35) 꼴이 아닌 태그에 RangeError 를 던진다. 러스트 판도 크롬(V8 의 CanonicalizeLanguageTag, ECMA-402 IsStructurallyValidLanguageTag)과 같은 검사를 하고 틀린 태그는 Err(FormatError::InvalidLanguageTag) 다. (밑줄 "EN_gb", 빈 글, 4 글자 언어 "root", 겹친 변이형이나 확장 글자, 끝이 빈 확장 "en-u" 같은 것. 오류 글도 크롬의 "Invalid language tag: ..." 와 같다)
  • fraction_digits 는 원본 toFixed 처럼 0 ~ 100 이 맞다. 넘겨도 던지지 않고 그 자릿수로 낸다.

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
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

함수functionpub fn format_number(value: f64, locale: &str) -> Result<String, FormatError>#0.3.2 부터since 0.3.2소스source

천 단위 구분 기호를 붙여 반환. (12480 -> "12,480", 원본 기본 locale 은 "en-US")

Returns with thousands separators. (12480 -> "12,480", the original default locale is "en-US")

valuef64
표기할 수.Number to display.
locale&str
언어 태그. ("en-US", "ko-KR" 처럼, 대소문자를 가리지 않는다. 표에 없으면 시스템 언어, 그것도 표에 없으면 en-US 로 쓴다)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)

반환ReturnsResult<String, FormatError> 로캘 표기 글. (소수는 0 ~ 3 자리로 반 올림하고 끝의 0 은 뺀다. NaN 은 로캘의 NaN 글, 무한대는 ∞) 언어 태그가 BCP 47 꼴이 아니면 원본의 RangeError 처럼 Err(FormatError::InvalidLanguageTag). (밑줄 "en_US", 빈 글 같은 것)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)

짝Counterpart: vanilla.js formatNumber

예제Example로캘마다 다른 소수점과 묶음 기호Decimal point and grouping symbols that differ by locale
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());
함수functionpub fn format_number_with_unit(value: f64, unit_suffix: &str, locale: &str) -> Result<String, FormatError>#0.4.0 부터since 0.4.0소스source

천 단위 구분 + 단위 접미사. (1200000, "원" -> "1,200,000원", 원본 기본 locale 은 "ko-KR")

Thousands separators + unit suffix. (1200000, "won" -> "1,200,000won", the original default locale is "ko-KR")

valuef64
표기할 수.Number to display.
unit_suffix&str
뒤에 붙일 단위 글. (사이에 공백을 넣지 않는다)Unit string appended at the end. (no space in between)
locale&str
언어 태그. (format_number 와 같다)Language tag. (same as format_number)

반환ReturnsResult<String, FormatError> format_number 의 글 뒤에 unit_suffix 를 붙인 글. 언어 태그가 틀리면 format_number 처럼 Err(FormatError::InvalidLanguageTag).The format_number text with unit_suffix appended. Err(FormatError::InvalidLanguageTag) for an invalid language tag, like format_number.

짝Counterpart: vanilla.js formatNumberWithUnit

예제Example골드와 점수 단위Gold and point units
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");
함수functionpub fn format_compact_number(value: f64, fraction_digits: usize) -> String#0.4.0 부터since 0.4.0소스source

큰 수를 짧게 줄여 반환. (1234 -> "1.2K", 5600000 -> "5.6M", 원본 기본 fractionDigits 는 1)

  • 반올림한 글이 1000 이 되면 Intl 의 compact 표기처럼 다음 단위로 올린다. (999999 -> "1M")

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")
valuef64
표기할 수. (음수는 절대값을 줄여 앞에 - 를 붙인다)Number to display. (negatives shorten the absolute value and prepend -)
fraction_digitsusize
줄인 수의 소수 자릿수. (끝의 0 은 뺀다, 절대값이 1000 미만이면 쓰지 않는다)Number of decimal digits of the shortened number. (trailing zeros removed, not used if the absolute value is under 1000)

반환ReturnsString 절대값이 1000 이상이면 K, 1000000 이상이면 M, 1000000000 이상이면 B 를 붙여 줄인 글. 1000 미만은 String(수) 꼴 그대로다. (반올림은 toFixed 꼴이고, 반올림해 1000 이 되면 다음 단위로 올려 999999 는 "1M", NaN 은 "NaN")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")

짝Counterpart: vanilla.js formatCompactNumber

예제Example단위 경계와 반올림Unit boundaries and rounding
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");
함수functionpub fn format_padded_number(value: f64, digit_count: usize, minimum_value: f64, maximum_value: f64) -> String#0.4.0 부터since 0.4.0소스source

값을 범위로 자르고 자릿수를 0 으로 채워 반환. (7세그먼트 카운터 표기 등)

  • format_padded_number(7.0, 3, ..) -> "007", format_padded_number(-5.0, 3, ..) -> "-05"
  • 원본 기본 범위는 minimum_value = f64::NEG_INFINITY, maximum_value = f64::INFINITY

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
valuef64
표기할 수.Number to display.
digit_countusize
전체 자릿수. (음수면 - 기호도 한 자리로 센다)Total number of digits. (for negatives the - sign counts as one digit)
minimum_valuef64
아래 끝. (끝 없이 쓰려면 f64::NEG_INFINITY)Lower bound. (f64::NEG_INFINITY for no bound)
maximum_valuef64
위 끝. (끝 없이 쓰려면 f64::INFINITY)Upper bound. (f64::INFINITY for no bound)

반환ReturnsString 범위로 자르고 앞을 0 으로 채운 글. (자릿수보다 길면 자르지 않는다. 소수, NaN, 지수 꼴도 String(수) 글을 그대로 채운다, 값이나 끝이 NaN 이면 NaN)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)

짝Counterpart: vanilla.js formatPaddedNumber

예제Example세 자리 카운터Three-digit counter
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");
함수functionpub fn format_minutes_seconds(total_seconds: f64) -> String#0.4.0 부터since 0.4.0소스source

초를 "분:초" 표기로 반환. (75 -> "1:15")

Returns seconds as "min:sec". (75 -> "1:15")

total_secondsf64
전체 시간. (초, 소수는 버리고 음수는 0 으로 친다)Total time. (seconds, decimals are dropped and negatives count as 0)

반환ReturnsString "분:초" 글. (초는 두 자리, 분은 60 을 넘어도 그대로. NaN 은 "NaN:NaN")"minutes:seconds" string. (seconds are two digits, minutes stay as is even past 60. NaN is "NaN:NaN")

짝Counterpart: vanilla.js formatMinutesSeconds

FormatErrorenum traits Clone, Debug, PartialEq, Eq, std::fmt::Display, std::error::Error

소스source

표기 오류. (원본이 던지는 RangeError 자리)

Formatting error. (where the original throws a RangeError)

예제Example틀린 언어 태그Invalid language tag
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");
이름Name값Value설명Description
InvalidLanguageTagInvalidLanguageTag(String)언어 태그가 BCP 47(유니코드 로캘 식별자) 꼴이 아니다. (원본 RangeError "Invalid language tag: ..." 의 태그 글) - 태그 글은 크롬이 오류에 찍는 것과 같다: 앞의 언어 식별자 조각이 틀리면 받은 그대로, 뒤의 확장이나 겹침이 틀리면 소문자로 바꾼 것.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.