JavaScript·100 questions

How to work with numbers?

Answer

Working with numbers in JavaScript covers many scenarios—from basic arithmetic operations to complex mathematical modeling and processing large volumes of data. The language provides built-in tools for safe conversion and formatting of numbers.

For safe conversion of strings into numeric values, the global functions `parseInt()` for integers and `parseFloat()` for floating-point numbers are used. Checking the validity of numeric data is performed using the `Number.isNaN()` and `Number.isFinite()` methods.

When you need to format a number for display, for example, to limit the number of decimal places in financial calculations, the `toFixed(digits)` method is irreplaceable. It returns a string with a specified number of decimal places, while the `toPrecision()` method controls the overall precision of the number.

Extensive capabilities for mathematical calculations are provided by the built-in `Math` object. It contains methods for rounding (`round()`), rounding down (`floor()`), rounding up (`ceil()`), as well as the `random()` method for generating random numbers.

The `Math.random()` method generates random numbers in the range from zero to one, which is often used in game algorithms, password generators, and automated tests. By combining it with other methods, you can obtain random integers within a specified range.

To work with arbitrary-precision integers that go beyond the standard safe number range (exceeding `Number.MAX_SAFE_INTEGER`), the primitive type `BigInt` was added to modern JavaScript. It is created by appending the `n` suffix to a number or by calling the `BigInt()` function, allowing you to perform precise calculations with huge integers without loss of precision.

Was this answer helpful?

More questions in this topic

Related questions from other topics