1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 21:08:12 +00:00

LibJS: Publicly expose double_to_string and rename it number_to_string

Rename it to match the name used by the spec.

Add an override mode to skip formatting numbers with an exponential sign
(e.g. 1e23). This mode is needed by Number and Intl.NumberFormat, who
don't call out a specific number-to-string method to use (they just say
to make "the String consisting of the digits of n").
This commit is contained in:
Timothy Flynn 2022-11-04 11:33:26 -04:00 committed by Linus Groh
parent efe82e5c91
commit 9620a092de
2 changed files with 13 additions and 4 deletions

View file

@ -71,7 +71,7 @@ ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs)
// 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring
// Implementation for radix = 10
static String double_to_string(double d)
String number_to_string(double d, NumberToStringMode mode)
{
auto convert_to_decimal_digits_array = [](auto x, auto& digits, auto& length) {
for (; x; x /= 10)
@ -116,8 +116,12 @@ static String double_to_string(double d)
if (sign)
builder.append('-');
// Non-standard: Intl needs number-to-string conversions for extremely large numbers without any
// exponential formatting, as it will handle such formatting itself in a locale-aware way.
bool force_no_exponent = mode == NumberToStringMode::WithoutExponent;
// 6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then
if (n >= -5 && n <= 21) {
if ((n >= -5 && n <= 21) || force_no_exponent) {
// a. If n ≥ k, then
if (n >= k) {
// i. Return the string-concatenation of:
@ -299,7 +303,7 @@ String Value::typeof() const
String Value::to_string_without_side_effects() const
{
if (is_double())
return double_to_string(m_value.as_double);
return number_to_string(m_value.as_double);
switch (m_value.tag) {
case UNDEFINED_TAG:
@ -337,7 +341,7 @@ ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm)
ThrowCompletionOr<String> Value::to_string(VM& vm) const
{
if (is_double())
return double_to_string(m_value.as_double);
return number_to_string(m_value.as_double);
switch (m_value.tag) {
case UNDEFINED_TAG: