Skip to content

Commit

Permalink
Mention number stringification rounding behavior (#34380)
Browse files Browse the repository at this point in the history
* Mention number stringification rounding behavior

* Update files/en-us/web/javascript/reference/global_objects/number/tostring/index.md

Co-authored-by: sideshowbarker <[email protected]>

---------

Co-authored-by: sideshowbarker <[email protected]>
  • Loading branch information
Josh-Cena and sideshowbarker committed Jun 24, 2024
1 parent 2198e26 commit 2de0ebb
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ browser-compat: javascript.builtins.Number.toFixed

{{JSRef}}

The **`toFixed()`** method of {{jsxref("Number")}} values formats this number using [fixed-point notation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic).
The **`toFixed()`** method of {{jsxref("Number")}} values returns a string representing this number using [fixed-point notation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) with the specified number of decimal places.

{{EmbedInteractiveExample("pages/js/number-tofixed.html")}}

Expand All @@ -25,7 +25,7 @@ toFixed(digits)

### Return value

A string representing the given number using fixed-point notation.
A string representing the given number using fixed-point notation. Scientific notation is used if the number's magnitude (ignoring sign) is greater than or equal to 10<sup>21</sup> (same return value as {{jsxref("Number.prototype.toString()")}}).

### Exceptions

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ browser-compat: javascript.builtins.Number.toPrecision

{{JSRef}}

The **`toPrecision()`** method of {{jsxref("Number")}} values returns a string representing
this number to the specified precision.
The **`toPrecision()`** method of {{jsxref("Number")}} values returns a string representing this number to the specified number of significant digits.

{{EmbedInteractiveExample("pages/js/number-toprecision.html")}}

Expand All @@ -23,17 +22,12 @@ toPrecision(precision)

- `precision` {{optional_inline}}
- : An integer specifying the number of significant digits.
- {{jsxref("TypeError")}}
- : Thrown if this method is invoked on an object that is not a {{jsxref("Number")}}.

### Return value

A string representing a {{jsxref("Number")}} object in fixed-point or exponential
notation rounded to `precision` significant digits. See the discussion of
rounding in the description of the {{jsxref("Number.prototype.toFixed()")}} method,
which also applies to `toPrecision()`.

If the `precision` argument is omitted, behaves as
{{jsxref("Number.prototype.toString()")}}. If the `precision` argument is a
non-integer value, it is rounded to the nearest integer.
A string representing the given number, using the given number of significant digits. Scientific notation is used if the exponent is greater than or equal to `precision` or less than -6. Has the same behavior as {{jsxref("Number.prototype.toString()")}} if the `precision` argument is omitted.

### Exceptions

Expand All @@ -45,22 +39,32 @@ non-integer value, it is rounded to the nearest integer.
### Using `toPrecision`

```js
// This number has exponent 0, so it will never use exponential notation
let num = 5.123456;

console.log(num.toPrecision()); // '5.123456'
console.log(num.toPrecision(5)); // '5.1235'
console.log(num.toPrecision(2)); // '5.1'
console.log(num.toPrecision(1)); // '5'

// This number has exponent -4, so it will never use exponential notation
num = 0.000123;

console.log(num.toPrecision()); // '0.000123'
console.log(num.toPrecision(5)); // '0.00012300'
console.log(num.toPrecision(2)); // '0.00012'
console.log(num.toPrecision(1)); // '0.0001'

// note that exponential notation might be returned in some circumstances
console.log((1234.5).toPrecision(2)); // '1.2e+3'
// This number has exponent 3, so it will use exponential notation if precision is less than 4
num = 1234.5;
console.log(num.toPrecision(1)); // '1e+3'
console.log(num.toPrecision(2)); // '1.2e+3'
console.log(num.toPrecision(6)); // '1234.50'

// This number has exponent -7, so it will always use exponential notation
num = 0.00000012345;
console.log(num.toPrecision(1)); // '1e-7'
console.log(num.toPrecision(10)); // '1.234500000e-7'
```

## Specifications
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ toString(radix)

### Return value

A string representing the specified number value.
A string representing the specified number value. Scientific notation is used if radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 10<sup>21</sup> or less than 10<sup>-6</sup>.

### Exceptions

- {{jsxref("RangeError")}}
- : Thrown if `radix` is less than 2 or greater than 36.
- {{jsxref("TypeError")}}
- : Thrown if this method is invoked on an object that is not a {{jsxref("Number")}}.

## Description

Expand All @@ -50,6 +52,15 @@ console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21"
console.log((10 ** 21.5).toString(8)); // "526665530627250154000000"
```

The underlying representation for floating point numbers is base-2 scientific notation (see [number encoding](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding)). However, the `toString()` method doesn't directly use this most precise representation of the number value. Rather, the algorithm uses the least number of significant figures necessary to distinguish the output from adjacent number values. For example, if the number is large, there will be many equivalent string representations of the same floating point number, and `toString()` will choose the one with the most 0s to the right (for any given radix).

```js
console.log((1000000000000000128).toString()); // "1000000000000000100"
console.log(1000000000000000100 === 1000000000000000128); // true
```

On the other hand, {{jsxref("Number.prototype.toFixed()")}} and {{jsxref("Number.prototype.toPrecision()")}} allow you to specify the precision and can be more precise than `toString()`.

The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to number values.

Because `Number` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation.
Expand Down

0 comments on commit 2de0ebb

Please sign in to comment.