Js rounding. Simple javascript rounding rules

This article will take a closer look at numbers, mathematical operators, ways to convert a number to a string and vice versa, as well as many other important points.

IsFinite function

The isFinite function allows you to check if an argument is finite.

In response, this function returns false if the argument is Infinity, -Infinity, NaN, or will be cast to one of these special numeric values. Otherwise, this function will return true.

IsFinite (73); // true isFinite (-1/0); // false isFinite (Infinity); // false isFinite (NaN); // false isFinite ("Text"); // false

In addition to the global isFinite function, JavaScript also has a Number.isFinite method. Unlike isFinite, it does not force the argument to a number.

IsFinite ("73"); // true Number.isFinite ("73"); // false

IsNaN function

The isNaN function is designed to determine if an argument is a number or can be converted to it. If so, the isNaN function returns false. Otherwise, it returns true.

IsNaN (NaN); // true isNaN ("25px"); // true, because 20px is not the isNaN number (25.5); // false isNaN ("25.5"); // false isNaN (""); // false, because space or several spaces are converted to 0 isNaN (null); // false, because null is converted to 0 isNaN (true); // false, because true is converted to 1 isNaN (false); // false, because false is converted to 0

If this action needs to be performed without type casting, then use the Number.isNaN method. This method has been introduced into the language since ECMAScript 6.

How can I explicitly convert a string to a number?

You can explicitly convert a string to a number using the following methods:

1. Use unary + operatorto be placed before the value.

+ "7.35"; // 7.35 + "text"; // NaN

This method ignores leading and trailing spaces and \\ n (line feed).

+ "7.35"; //7.35 + "7.35 \\ n"; //7.35

Using this method, you need to pay attention to the fact that an empty string or a string consisting of spaces and \\ n is translated to the number 0. In addition, it also converts the null data type and boolean values \u200b\u200bto a number.

Null; // 0 + true; // 1 + false; // 0 + ""; // 0

2. The parseInt function. This function is designed to convert argument to an integer... As opposed to using unary operator +, this method allows you to convert a string to a number in which not all characters are numeric... It starts converting the string starting at the first character. And as soon as it encounters a character that is not digital, this function stops its work and returns the resulting number.

ParseInt ("18px"); // 18 parseInt ("33.3%"); // 33

This function can work with different number systems (binary, octal, decimal, hexadecimal). The radix is \u200b\u200bspecified using 2 arguments.

ParseInt ("18px", 10); // 18 parseInt ("33.3%", 10); // 33 parseInt ("101", 2); // 5 parseInt ("B5", 16); // 181

In addition to the parseInt function, JavaScript has a Number.parseInt method. This method is no different from the parseInt function and was introduced in JavaScript with the ECMASCRIPT 2015 specification (6).

3. The parseFloat function. ParseFloat is similar to parseInt, except that it converts the argument to a fraction.

ParseFloat ("33.3%"); //33.3

In addition, the parseFloat function, unlike parseInt, does not have 2 arguments, and therefore it always tries to consider the string as a number in decimal notation.

ParseFloat ("3.14"); parseFloat ("314e-2"); parseFloat ("0.0314E + 2");

In addition to the parseFloat function, JavaScript has a Number.parseFloat method. This method is no different from the parseFloat function and was introduced in JavaScript with the ECMASCRIPT 2015 specification (6).

Convert number to string

You can convert a number to a string using the toString method.

(12.8) .toString (); //"12.8 "

The toString method also allows you to specify the base of the number system, taking into account which it is necessary to explicitly cast the number to a string:

(255) .toString (16); // "ff"

How to check if a variable is a number

You can determine if the value of a variable is a number using one of the following methods:

1.Using the isNaN and isFinite functions:

// myVar is a variable if (! isNaN (parseFloat (myVar)) && isFinite (parseFloat (myVar))) (// myVar is a number or can be cast to it);

As a function:

// function function isNumeric (value) (return! isNaN (parseFloat (value)) && isFinite (parseFloat (value));) // use var myVar \u003d "12px"; console.log (isNumeric (myVar)); // true

This method allows you to determine whether the specified value is a number or can be converted to it. This option does not treat an empty string, a string of spaces, , Infinity, -Infinity, true or false as a number.

2.Using the typeof operator and isFinite, isNaN functions:

// function that checks if the value is a number function isNumber (value) (return typeof value \u003d\u003d\u003d "(! LANG: number" && isFinite(value) && !isNaN(value); }; // использование функции isNumber isNumber(18); //true // использование функций для проверки текстовых значений isNumber(parseFloat("")); //false isNumber(parseFloat("Infinity")); //false isNumber(parseFloat("12px")); //true !}

This function determines whether the specified value is of type Number and one of the special values \u200b\u200bInfinity, -Infinity, and NaN. If so, then this function returns true.

3.Using the ECMAScript 6 Number.isInteger (value) method. This method allows you to determine if the specified value is an integer.

Number.isInteger ("20"); // false, because this method does not perform a line feed to Number.isInteger (20); // true, because the given value is a number

Even and odd numbers

You can check whether a number is even or odd using the following functions:

// Function for checking the number for evenness function isEven (n) (return n% 2 \u003d\u003d 0;) // Function for checking the number for oddness function isOdd (n) (return Math.abs (n% 2) \u003d\u003d 1; )

But before doing such a check, it is advisable to make sure that the specified value is a number:

Value \u003d 20; if (Number.isInteger (value)) (if (isEven (value)) (console.log ("Number" + value.toString () + "- even");))

Javascript primes

Let's consider an example in which we display primes from 2 to 100 using Javascript.

// A function that checks if the number is prime function isPrime (value) (if (isNaN (value) ||! IsFinite (value) || value% 1 || value< 2) return false; var max=Math.floor(Math.sqrt(value)); for (var i = 2; i< = max; i++) { if (value%i==0) { return false; } } return true; } // создать массив, который будет содержать простые числа от 2 до 100 var primaryNumber = ; for (var i = 2; i <= 100; i++) { if(isPrime(i)) primaryNumber.push(i); } // вывести в консоль простые числа от 2 до 100 console.log(primaryNumber);

Rounding a number in Javascript

There are various ways to round a fractional number to an integer value in JavaScript.

1. Using specially designed methods for this Math.floor, Math.ceil and Math.round. The Math.floor method rounds the fractional number down to the nearest integer, i.e. simply discards the fractional part. Math.ceil rounds a fractional number up to the nearest integer. Math.round rounds a number up or down depending on the value of the fractional part. If the fractional part is greater than or equal to 0.5, then up, otherwise the curl is down.

Console.log (Math.floor (7.9)); // 7 console.log (Math.ceil (7.2)); // 8 console.log (Math.round (7.5)); //8

2. Using the toFixed (precision) method. This method rounds the fractional part of a number to the specified precision. The rounding result is returned as a string.

Console.log (7.987.toFixed (2)); //"7.99 "

If there are not enough decimal places to form the specified precision of the number, then it is padded with zeros.

Console.log (7.987.toFixed (5)); //"7.98700 "

3. Through the toPrecision method. This method represents a number with the specified precision. Moreover, he can round off not only the fractional, but also the whole part of the number. This method can represent the resulting number, depending on the result, with a fixed point or in exponential form.

Console.log ((1001) .toPrecision (2)); //"1.0e+3 "console.log ((1001) .toPrecision (5)); //"1001.0 "console.log ((12.4) .toPrecision (1)); // "1e + 1" console.log ((12.4) .toPrecision (2)); // "12" console.log ((12.4) .toPrecision (3)); //"12.4 "console.log ((12.4) .toPrecision (5)); //"12.400 "

4. Using logical operators NOT or OR.

// via double logical negation console.log (~~ 7.9); // 7 // by using logical OR with zero: console.log (7.9 ^ 0); // 7

Integer and fractional part of a number

You can get the integer part of a number using the Math.floor () method and parseInt ():

Console.log (Math.floor (7.21)); // 7 console.log (parseInt (7.21)); // 7

You can get the fractional part of a number using the percentage (%) operator. This operator returns the remainder that will be obtained by dividing the first number by the second. In this case, 1 must be used as the 2 number.

Console.log (7.21% 1); // 0.20999999999999996 // accurate to 2 decimal places console.log ((7.21% 1) .toFixed (2)); // "0.21"

In addition, the fractional part can also be obtained using calculations:

Var number \u003d 7.21; var fractionNumber \u003d number - Math.floor (Math.abs (number)); console.log (fractionNumber); // 0.20999999999999996

Is the number even divisible

You can determine whether a number is evenly divisible using the percent operator:

Var number \u003d 9; // if the remainder of dividing number by 3 is 0, then yes, otherwise no if (number% 3 \u003d\u003d 0) (console.log ("Number" + number + "is divisible by 3");) else (console. log ("Number" + number + "is not divisible by 3");)

Formatting numbers

In JavaScript, the toLocaleString () method allows you to format the output of a number to match the regional (operating system) language settings.

For example, let's format the number according to the regional standards that are installed on the system by default:

Var number \u003d 345.46; console.log (number.toLocaleString ()); // "345.46"

For example, let's format the number in accordance with the regional standards of Russia (ru):

Console.log ((108.1) .toLocaleString ("ru-RU")); // "108,1"

This method can also be used to format a number as a currency:

Console.log ((2540.125) .toLocaleString ("ru-RU", (style: "currency", currency: "RUB"))); // "2 540.13 ₽" console.log ((89.3) .toLocaleString ("ru-RU", (style: "currency", currency: "USD"))); // "89.30 $" console.log ((2301.99) .toLocaleString ("ru-RU", (style: "currency", currency: "EUR"))); // "€ 2,301.99"

Number representation as percent:

Console.log ((0.45) .toLocaleString ("ru-RU", (style: "percent"))); // "45%"

Split the number into digits (useGrouping property):

Console.log ((125452.32) .toLocaleString ("ru-RU", (useGrouping: true))); // "125 452.32"

Print a number with a certain number of digits (2) after the decimal point:

Console.log ((1240.4564) .toLocaleString ("ru-RU", (minimumFractionDigits: 2, maximumFractionDigits: 2))); // "1 240.46"

Comparing numbers

JavaScript uses the following operators to compare numbers: \u003d\u003d (equal),! \u003d (Not equal),\u003e (greater than),< (меньше), >\u003d (greater than or equal),<= (меньше или равно).

For example, let's compare two numbers:

Console.log (2\u003e 3); // false console.log (5\u003e \u003d 3); // true

When comparing numbers with fractional parts, it is necessary to take into account the errors that may arise during these calculations.

For example, in JavaScript, the sum of numbers (0.2 + 0.4) is not 0.6:

Console.log ((0.2 + 0.4) \u003d\u003d 0.6); // false

Errors occur because all calculations are performed by a computer or other electronic device in the 2nd number system. Those. before performing any actions, the computer must first convert the numbers represented in the expression into 2 number system. But, not any fractional decimal number can be represented exactly in 2 number system.

For example, the number 0.25 10 is converted exactly to the binary system.

0.125 × 2 \u003d 0.25 | 0 0.25 × 2 \u003d 0.5 | 0 0.5 × 2 \u003d 1 | 1 0.125 10 \u003d 0.001 2

For example, the number 0.2 10 can be converted to 2 system only with a certain precision:

0.2 × 2 \u003d 0.4 | 0 0.4 × 2 \u003d 0.8 | 0 0.8 × 2 \u003d 1.6 | 1 0.6 × 2 \u003d 1.2 | 1 0.2 × 2 \u003d 0.4 | 0 0.4 × 2 \u003d 0.8 | 0 0.8 × 2 \u003d 1.6 | 1 0.6 × 2 \u003d 1.2 | 1 0.2 × 2 \u003d 0.4 | 0 0.4 × 2 \u003d 0.8 | 0 0.8 × 2 \u003d 1.6 | 1 0.6 × 2 \u003d 1.2 | 1 ... 0.2 10 \u003d 0.001100110011 ... 2

As a result, these errors will affect the calculation of the sum of two numbers and the comparison results. Those. it turns out that in fact JavaScript will see this entry as follows:

0.6000000000000001==0.6

When calculating or displaying numbers with a fractional part, you must always indicate the precision with which it must be done.

For example, compare numbers up to 2 decimal places using the toFixed () and toPrecision () methods:

// method toFixed () console.log ((0.2 + 0.4) .toFixed (2) \u003d\u003d (0.6) .toFixed (2)); // true // method toPrecision () console.log ((0.2 + 0.4) .toPrecision (2) \u003d\u003d (0.6) .toPrecision (2)); // true

Basic math operations

The following mathematical operators exist in JavaScript: + (addition), - (subtraction), * (multiplication), / (division),% (modulo), ++ (increase value by 1), - (decrease value by 1 ).

6 + 3 // 9 6-3 // 3 6 * 3 // 18 6/3 // 2 6% 3 // 0, i.e. 6: 3 \u003d 2 \u003d\u003e 6-3 * 2 \u003d\u003e rest (0) 5% 2 // 1, i.e. 5: 2 \u003d 2 (.5) \u003d\u003e 5-2 * 2 \u003d\u003e rest (1) 7.3% 2 //1.3, i.e. 7.3: 2 \u003d 3 (.65) \u003d\u003e 7.3-2 * 3 \u003d\u003e rest (1.3) // the sign of the result of the% operation is equal to the sign of the first value -9% 2.5 //-1.5, i.e. 9: 2.5 \u003d 3 (.6) \u003d\u003e 9-2.5 * 3 \u003d\u003e rest (1.5) -9% -2.5 //-1.5, i.e. 9: 2.5 \u003d 3 (.6) \u003d\u003e 9-2.5 * 3 \u003d\u003e rest (1.5) -2% 5 // - 2, i.e. 2: 5 \u003d 0 (.4) \u003d\u003e 2-5 * 0 \u003d\u003e rest (2) x \u003d 3; console.log (x ++); // prints 3, y sets 4 later console.log (x); // 4 x \u003d 3; console.log (++ x); // sets 4 and prints x \u003d 5; console.log (x--); // prints 5, y sets 4 later console.log (x); // 4 x \u003d 5; console.log (- x); // sets 4 and outputs In addition, JavaScript has combined operators: x + \u003d y (x \u003d x + y), x- \u003d y (x \u003d xy), x * \u003d y (x \u003d x * y), x / \u003d y (x \u003d x / y), x% \u003d y (x \u003d x% y). x \u003d 3; y \u003d 6; x + \u003d y; console.log (x); // 9 x \u003d 3; y \u003d 6; x- \u003d y; console.log (x); // - 3 x \u003d 3; y \u003d 6; x * \u003d y; console.log (x); // 18 x \u003d 3; y \u003d 6; x / \u003d y; console.log (x); //0.5 x \u003d 3; y \u003d 6; x% \u003d y; console.log (x); // 3

Often times, computations in JavaScript do not give exactly the results we want. Of course, we can do anything with the numbers - round up or down, set ranges, cut off unnecessary numbers to a certain number of decimal places, it all depends on what you want to do with this number in the future.

Why is rounding necessary?

One of the curious aspects of JavaScript is that it doesn't actually store integers, we are immediately working with floating point numbers. This, combined with the fact that many fractional values \u200b\u200bcannot be expressed in finite numbers of decimal places, in JavaScript we can get results like this:

0.1 * 0.2; > 0.020000000000000004 0.3 - 0.1 > 0.19999999999999998
For practical purposes, this inaccuracy does not matter at all, in our case we are talking about an error in quintillion parts, however, this may disappoint someone. We can get a slightly strange result when working with numbers that represent values \u200b\u200bof currencies, percentages, or file sizes. In order to correct these inaccuracies, we just need to be able to round off the results, while it is enough to set the decimal precision.

Rounding numbers has a practical application, we can manipulate a number in a certain range, for example, we want to round the value to the nearest integer, and not work only with the decimal part.

Rounding decimal numbers

To strip off the decimal number, use toFixed or the toPrecision method. They both take a single argument, which determines, respectively, how many significant digits (i.e. the total number of digits used in the number) or decimal places (the number after the decimal point) the result should include:
  1. If the argument is not defined for toFixed (), then by default it will be zero, which means 0 decimal places, the argument has a maximum value of 20.
  2. If no argument is given for toPrecision, the number is left untouched
let randNum \u003d 6.25; randNum.toFixed (); \u003e "6" Math.PI.toPrecision (1); \u003e "3" randNum \u003d 87.335; randNum.toFixed (2); \u003e "87.33" randNum \u003d 87.337; randNum.toPrecision (3); \u003e "87.3"
Both toFixed () and toPrecision () return a string representation of the result, not a number. This means that when the rounded value is summed with randNum, the strings will be concatenated, not the sum of the numbers:

Let randNum \u003d 6.25; let rounded \u003d randNum.toFixed (); // "6" console.log (randNum + rounded); \u003e "6.256"
If you want the result to have a numeric data type, then you will need to use parseFloat:

Let randNum \u003d 6.25; let rounded \u003d parseFloat (randNum.toFixed (1)); console.log (rounded); \u003e 6.3
Note that 5 values \u200b\u200bare rounded except in rare cases.

The toFixed () and toPrecision () methods are useful because they can not only strip off the fractional part, but also complete the decimal places, which is convenient when working with currency:

Let wholeNum \u003d 1 let dollarsCents \u003d wholeNum.toFixed (2); console.log (dollarsCents); \u003e "1.00"
Please note that toPrecision will give the result in exponential notation if the number of integers is greater than the precision itself:

Let num \u003d 123.435 num.toPrecision (2); \u003e "1.2e + 2"

How to avoid rounding errors with decimal numbers

In some cases, toFixed and toPrecision rounds the value 5 down and up:

Let numTest \u003d 1.005; numTest.toFixed (2); \u003e "1.00"
The above calculation result should have been 1.01, not 1. If you want to avoid this error, we can use the solution proposed by Jack L Moore, which uses exponential numbers to calculate:

Function round (value, decimals) (return Number (Math.round (value + "e" + decimals) + "e -" + decimals);)
Now:

Round (1.005.2); \u003e 1.01
If you want a more robust solution than the one shown above, you can head over to MDN.

Machine epsilon rounding

An alternative method for rounding decimal numbers was introduced in ES6. Machine epsilon rounding provides a reasonable margin of error when comparing two floating point numbers. Without rounding, comparisons can produce results similar to the following:

0.1 + 0.2 \u003d\u003d\u003d 0.3\u003e false
We use Math.EPSILON in our function to get the correct comparison:

Function epsEqu (x, y) (return Math.abs (x - y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }
The function takes two arguments: the first is the current calculation, the second is the expected result. It returns a comparison of the two:

EpsEqu (0.1 + 0.2, 0.3)\u003e true
All modern browsers already support ES6 math functions, but if you want support in browsers like IE 11 use polyfills.

Fractional clipping

All methods presented above know how to round to decimal numbers. In order to simply cut off the number to two decimal places, you must first multiply it by 100, and then divide the result by 100:

Function truncated (num) (return Math.trunc (num * 100) / 100;) truncated (3.1416)\u003e 3.14
If you want to accommodate any number of decimal places, you can use double bitwise negation:

Function truncated (num, decimalPlaces) (let numPowerConverter \u003d Math.pow (10, decimalPlaces); return ~~ (num * numPowerConverter) / numPowerConverter;)
Now:

Let randInt \u003d 35.874993; truncated (randInt, 3); \u003e 35.874

Rounding to the nearest number

To round a decimal up or down to the nearest number, whichever we are closest to, use Math.round ():

Math.round (4.3)\u003e 4 Math.round (4.5)\u003e 5
Note that “half the value,” 0.5 is rounded up according to the rules of mathematics.

Round down to nearest whole number

If you want to always round down, use Math.floor:

Math.floor (42.23); \u003e 42 Math.floor (36.93); \u003e 36
Note that rounding down works for all numbers, including negative ones. Imagine a skyscraper with an infinite number of floors, including those on the lower level (representing negative numbers). If you are in the elevator on the lower level between 2 and 3 (which is a value of -2.5), Math.floor will take you to -3:

Math.floor (-2.5); \u003e -3
But if you want to avoid this situation, use Math.trunc, which is supported in all modern browsers (except IE / Edge):

Math.trunc (-41.43); \u003e -41
On MDN you will find a polyfill that will provide support for Math.trunc in browsers and IE / Edge.

Round up to the nearest whole number

On the other hand, if you always need to round up, use Math.ceil. Again, remembering the infinite lift: Math.ceil will always go up, regardless of whether the number is negative or not:

Math.ceil (42.23); \u003e 43 Math.ceil (36.93); \u003e 37 Math.ceil (-36.93); \u003e -36

Rounding up / down as required

If we want to round to the nearest multiple of 5, the simplest way is to create a function that divides a number by 5, rounds it, and then multiplies it by the same amount:

Function roundTo5 (num) (return Math.round (num / 5) * 5;)
Now:

RoundTo5 (11); \u003e 10
If you want to round to multiples of your value, we use a more general function, passing in an initial value and a multiple:

Function roundToMultiple (num, multiple) (return Math.round (num / multiple) * multiple;)
Now:

Let initialNumber \u003d 11; let multiple \u003d 10; roundToMultiple (initialNumber, multiple); \u003e 10;

Fixing a number in a range

There are many cases where we want to get an x \u200b\u200bvalue that is within a range. For example, we may want a value between 1 and 100, but we get a value of 123. To fix this, we can use the minimum (returns the smallest of a set of numbers) and maximum (returns the largest of any set of numbers). In our example, the range is from 1 to 100:

Let lowBound \u003d 1; let highBound \u003d 100; let numInput \u003d 123; let clamped \u003d Math.max (lowBound, Math.min (numInput, highBound)); console.log (clamped); \u003e 100;
Again, we can reuse the operation and wrap it all into a function, let's use the solution suggested by Daniel X. Moore:

Number.prototype.clamp \u003d function (min, max) (return Math.min (Math.max (this, min), max););
Now:

NumInput.clamp (lowBound, highBound); \u003e 100;

Gaussian rounding

Gaussian rounding, also known as bank rounding, is where the rounding occurs to the nearest even. This rounding method works without statistical error. The best solution was suggested by Tim Down:

Function gaussRound (num, decimalPlaces) (let d \u003d decimalPlaces || 0, m \u003d Math.pow (10, d), n \u003d + (d? Num * m: num) .toFixed (8), i \u003d Math.floor (n), f \u003d n - i, e \u003d 1e-8, r \u003d (f\u003e 0.5 - e && f< 0.5 + e) ? ((i % 2 == 0) ? i: i + 1) : Math.round(n); return d ? r / m: r; }
Now:

GaussRound (2.5)\u003e 2 gaussRound (3.5)\u003e 4 gaussRound (2.57,1)\u003e 2.6
Decimal point in CSS:

Since JavaScript is often used to generate positional transformations on HTML elements, you might wonder what happens if we generate decimal values \u200b\u200bfor our elements:

#box (width: 63.667731993px;)
The good news is that modern browsers will consider decimal values \u200b\u200bin the box model, including in percentage or pixel units.

Sorting

Very often we have to sort some elements, for example, we have an array of game records, and they must be organized in descending order of the rank of the players. Unfortunately, the standard sort () method has some surprising limitations: it works well with commonly used English words, but breaks immediately when faced with numbers, unique characters, or uppercase words.

Sort alphabetically

It would seem that sorting an array alphabetically should be the simplest task:

Let fruit \u003d ["butternut squash", "apricot", "cantaloupe"]; fruit.sort (); \u003e "apricot", "butternut squash", "cantaloupe"]
However, we run into a problem as soon as one of the elements is uppercase:

Let fruit \u003d ["butternut squash", "apricot", "Cantalope"]; fruit.sort (); \u003e "Cantaloupe", "apricot", "butternut squash"]
This is because, by default, the sorter compares the first character represented in Unicode. Unicode is a unique code for any character, regardless of platform, regardless of program, regardless of language. For example, if you look at the code table, the character "a" has the value U + 0061 (in hexadecimal system 0x61), while the character "C" has the code U + 0043 (0x43), which comes earlier in the Unicode table than the character "A".

To sort an array, which can contain mixed case of first letters, we need to either convert all elements temporarily to lower case, or define our own sort order using the localeCompare () method with some arguments. As a rule, for such a case, it is better to immediately create a function for repeated use:

Function alphaSort (arr) (arr.sort (function (a, b) (return a.localeCompare (b, "en", ("sensitivity": "base"));));) let fruit \u003d ["butternut squash "," apricot "," Cantaloupe "]; alphaSort (fruit)\u003e
If you want to get an array sorted in reverse alphabetical order, just swap the positions of a and b in the function:

Function alphaSort (arr) (arr.sort (function (a, b) (return b.localeCompare (a, "en", ("sensitivity": "base"));));) let fruit \u003d ["butternut squash "," apricot "," Cantaloupe "]; alphaSort (fruit)\u003e ["Cantaloupe", "butternut squash", "apricot"]
Here it is worth noting that localeCompare is used with arguments, you also need to remember that it is supported by IE11 +, for older versions of IE, we can use it without arguments, and in lower case:

Function caseSort (arr) (arr.sort (function (a, b) (return a.toLowerCase (). LocaleCompare (b.toLowerCase ());));) let fruit \u003d ["butternut squash", "apricot", "Cantaloupe"]; caseSort (fruit)\u003e ["apricot", "butternut squash", "Cantaloupe"]

Numeric sort

All this does not apply to the example that we talked about above about the array of game records. With some numeric arrays, sorting works just fine, but at some point the result can be unpredictable:

Let highScores \u003d; highScores.sort (); \u003e
The fact is that the sort () method performs a lexicographic comparison: which means that the numbers will be converted to a string and the comparisons will be performed again by matching the first character of this string in Unicode table character order. Therefore, we again need to define our sort order:

Let highScores \u003d; highScores.sort (function (a, b) (return a - b;)); \u003e
Again, to sort the numbers in reverse order, swap the positions of a and b in the function.

Sorting a JSON-like structure

Finally, if we have a JSON-like data structure represented as an array of game records:

Let scores \u003d [("name": "Daniel", "score": 21768), ("name": "Michael", "score": 33579), ("name": "Alison", "score": 38395 )];
In ES6 +, you can use arrow functions:

Scores.sort ((a, b) \u003d\u003e b.score - a.score));
For older browsers that don't have this support:

Scores.sort (function (a, b) (return a.score - b.score));
As you can see, sorting in JavaScript is not an obvious thing, I hope these examples make life easier somehow.

Working with power functions

Exponentiation is an operation initially defined as the result of multiple multiplication of a natural number by itself, the square root of a is the number that gives a when squared. We could use these functions all the time in everyday life in math lessons, including when calculating areas, volumes, or even in physical modeling.

In JavaScript, the exponential function is represented as Math.pow (), in the new ES7 standard, a new exponentiation operator is introduced - "* *".

Exponentiation

To raise a number to the nth power, use the Math.pow () function, where the first argument is the number to be raised to the power, the second argument is the exponent:

Math.pow (3,2)\u003e 9
This form of notation means 3 squared, or 3 × 3, which leads to the result 9. You can give another example, of course:

Math.pow (5.3); \u003e 125
That is, 5 cubed, or 5 × 5 × 5, equals 125.

ECMAScript 7 is the next version of JavaScript, in principle, we can use the new proposed exponentiation operator - * *, this notation can be more descriptive:

3 ** 2 > 9
Currently, support for this operator is rather limited, so it is not recommended to use it.

The power function can come in handy in a variety of situations. A simple example, calculating the number of seconds in an hour: Math.pow (60,2).

Square and cube root

Math.sqrt () and Math.cbrt () are the opposite of the Math.pow () function. Remember that the square root of a is the number that gives a when squared.

Math.sqrt (9)\u003e 3
At the same time, the cube root of the number a is the number that gives a when raised to a cube.

Math.cbrt (125)\u003e 5
Math.cbrt () was introduced to the JavaScript specification very recently and is therefore only supported in modern browsers: Chrome 38+, Firefox and Opera 25+, and Safari 7.1+. You will notice that Internet Explorer is not on this list, however you will find a polyfill on MDN.

Examples of

Of course, we can also use non-integer values \u200b\u200bin one of these functions:

Math.pow (1.25, 2); \u003e 1.5625 Math.cbrt (56.57)\u003e 3.8387991760286138
Note that this also works fine for negative argument values:

Math.pow (-5,2)\u003e 25 Math.pow (10, -2)\u003e 0.01
However, for a square root, this won't work:

Math.sqrt (-9)\u003e NaN
We know from mathematical analysis that an imaginary number is understood as the square roots of negative numbers. And this may lead us to another technique for working with complex numbers, but that's another story.

You can use fractional values \u200b\u200bin Math.pow () to find the square and cube roots of numbers. The square root uses an exponent of 0.5:

Math.pow (5, 0.5); // \u003d Math.sqrt (5) \u003d 5 ** (1/2)\u003e 2.23606797749979
However, due to the vagaries of floating point, you cannot accurately guess the correct result:

Math.pow (2.23606797749979.2)\u003e 5.000000000000001
In such situations, you will have to resort to truncating the signs from the number or rounding to some value.

Some, for some unknown reason in JavaScript, confuse the Math.pow () function with Math.exp (), which is an exponential function for numbers in general. Note: in English, "exponent" translates as "exponent", so this is more likely to refer to English speakers, although there are alternative names for the exponent, such as index, power.

Mathematical constants

Working with math in JavaScript is made easier by a number of built-in constants. These constants are properties of the Math object. Note that constants are written in uppercase, not CamelCase notation.

Math.abs, parseInt, parseFloat

Working with numbers in JavaScript can be a lot more complicated than it sounds. The obtained values \u200b\u200bdo not always fall within the expected ranges, sometimes the result may not be what we expected at all.

Math.abs ()

The Math.abs () method returns the absolute value of a number, which reminds us of the analogous math function for the modulus of a number.

Let newVal \u003d -57.64; Math.abs (newVal); \u003e 57.64
Math.abs (0) always returns zero, but if we put a minus sign in front of the -Math.abs (NUM) function, we will always be negative.

Math.abs (0); \u003e -0

parseInt ()

We know that JavaScript understands that "15" is a string, not a number, and, for example, when parsing CSS properties using JavaScript, or getting some value from an unprepared array, our results can be unpredictable. We could get a string represented as "17px" as input, and this is not uncommon for us. The question is how to convert this string to an actual value and use it in further calculations.

Syntax: parseInt (string, radix);

The parseInt function converts the first argument passed to it to a string, interprets it, and returns an integer or NaN value. The result (if not NaN) is an integer and is the first argument (string), treated as a number in the specified number system (radix). For example, base 10 indicates a conversion from decimal, 8 to octal, 16 to hex, and so on. If the base is greater than 10, then letters are used to denote numbers greater than 9. For example, hexadecimal numbers (base 16) use the letters A through F.

Let's consider an example of working with CSS properties, where, relatively speaking, we can get such a value:

Let elem \u003d document.body; let centerPoint \u003d window.getComputedStyle (elem) .transformOrigin; \u003e "454px 2087.19px"
We can split values \u200b\u200bby spaces:

Let centers \u003d centerPoint.split (""); \u003e ["454px", "2087.19px"]
However, each element is still a string, we can get rid of this by applying our function:

Let centerX \u003d parseInt (centers, 10); \u003e 454 let centerY \u003d parseInt (centers, 10); \u003e 2087
As you can see, as the second argument, we indicate the number system to which the number will be converted, this parameter is optional, but it is recommended to use it in case you do not know which string will come to the input.

parseFloat ()

From the example above, you may have noticed that parseInt discards the fractional part. In our case, parseFloat is able to work with floating point numbers. Again, this can be useful when parsing CSS and other tasks, especially when dealing with floating point percentages.

Syntax: parseFloat (string)

Let FP \u003d "33.33333%"; console.log (parseFloat (FP)); \u003e 33.33333
Note that there is no second argument in the parseFloat syntax.

We understand that parseInt () and parseFloat () are extremely useful functions, it is important to keep in mind that there are some errors here, so it is necessary to check the range of expected values \u200b\u200band ultimately analyze the result to ensure that the obtained values \u200b\u200bare correct.
Send anonymously

Calculations often produce results that fall outside the desired ranges. As a result, you need to implement JavaScript rounding to a certain value.

Why round off numbers?

JavaScript does not store integers because their values \u200b\u200bare represented as floating point numbers. Many fractions cannot be represented by a finite number of decimal places, so JavaScript can generate results like the one below:

0.1 * 0.2; > 0.020000000000000004

In practice, this will not make any difference, since we are talking about an error of 2 quintillion. However, this can affect the result when working with numbers that represent currency values, percentages, or file size. Therefore, you need to do or to a certain decimal place.

Rounding decimal numbers

To "trim" a decimal number, use the toFixed () or toPrecision () methods. They both take one argument, which specifies the number of significant and decimal places to include in the result:

  • if no argument is defined for toFixed (), the default is 0, that is, no decimal places; the maximum value of the argument is 20;
  • if no argument is specified for toPrecision (), the number is not changed.

var randNum \u003d 6.25; randNum.toFixed (); \u003e "6" Math.PI.toPrecision (1); \u003e "3" var randNum \u003d 87.335; randNum.toFixed (2); \u003e "87.33" var randNum \u003d 87.337; randNum.toPrecision (3); \u003e "87.3"

Note

Both toFixed () and toPrecision return a rounded string representation of the result, not a number. This means that adding rounded to randNum will result in string concatenation rather than a single number:

console.log (randNum + rounded); \u003e "6.256"

If you want JavaScript to round to the nearest hundredth, use parseFloat ():

var randNum \u003d 6.25; var rounded \u003d parseFloat (randNum.toFixed (1)); console.log (rounded); \u003e 6.3

toFixed () and toPrecision () are also useful methods for truncating large numbers of decimal places. This is useful when working with numbers that represent monetary units:

var wholeNum \u003d 1 var dollarsCents \u003d wholeNum.toFixed (2); console.log (dollarsCents); \u003e "1.00"

Note that if there are more digits in the number than specified by the precision parameter, toPrecision will return the result in scientific format:

var num \u003d 123.435 num.toPrecision (2); \u003e "1.2e + 2"

How to avoid errors when rounding decimals

In some cases toFixed and toPrecision implement JavaScript rounding 5 down, and not to more:

var numTest \u003d 1.005; numTest.toFixed (2); \u003e 1;

The above example should result in 1.01, not 1. If you want to avoid this error, I recommend using exponential numbers:

function round (value, decimals) (return Number (Math.round (value + "e" + decimals) + "e -" + decimals);)

Application:

round (1.005.2); \u003e 1.01

If you need an even more reliable solution than rounding, it is available at MDN.

Epsilon rounding

Alternative method JavaScript rounding to tenths was introduced in ES6 ( also known as JavaScript 2015). « Machine epsilon»Provides a reasonable margin of error when comparing two floating point numbers. Without rounding, comparisons can produce results similar to the following:

0.1 + 0.2 \u003d\u003d\u003d 0.3\u003e false

Math.EPSILON can be used in a function to get a correct comparison:

function epsEqu (x, y) (return Math.abs (x - y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }

The function takes two arguments: one contains calculations, the second is the expected (rounded) result. It returns a comparison of these two parameters:

epsEqu (0.1 + 0.2, 0.3)\u003e true

All modern browsers support ES6 math functions. But if you need to provide support in older browsers, then you need to use polyfills.

Truncating decimal numbers

All the methods presented earlier perform JavaScript rounding to tenths... To truncate a positive number to two decimal places, multiply it by 100, truncate it again, and then divide the result by 100, you need:

function truncated (num) (return Math.trunc (num * 100) / 100;) truncated (3.1416)\u003e 3.14

If you need something more flexible, you can use the bitwise operator:

function truncated (num, decimalPlaces) (var numPowerConverter \u003d Math.pow (10, decimalPlaces); return ~~ (num * numPowerConverter) / numPowerConverter;)

Using:

var randInt \u003d 35.874993; truncated (randInt, 3); \u003e 35.874

Rounding to the nearest number

To carry out JavaScript rounding to integer, used by Math.round ():

Math.round (4.3)\u003e 4 Math.round (4.5)\u003e 5

Note that " half values“Such as .5 are rounded up.

Round down to the nearest whole number

If you want to round down, use the Math.floor () method:

Math.floor (42.23); \u003e 42 Math.floor (36.93); \u003e 36

Rounding down has one direction for all numbers, including negative ones. This can be imagined as a skyscraper with an infinite number of floors, including below the level of the foundation ( representing negative numbers). If you are in the elevator between basement floors 2 and 3 ( which corresponds to a value of -2.5), Math.floor takes you to floor -3:

Math.floor (-2.5); \u003e -3

If you need to avoid this, use JavaScript Math rounding with Math.trunc (), which is supported in all modern browsers (except IE / Edge):

Math.trunc (-41.43); \u003e -41

MDN also provides 3-line polyfill to provide Math.trunc support in older browsers and IE / Edge.

Round up to the nearest whole number

If you want to round up decimal numbers, use Math.ceil. This method can also be thought of as an endless lift: Math.ceil always takes you up, regardless of whether the number is negative or positive:

Math.ceil (42.23); \u003e 43 Math.ceil (36.93); \u003e 37 Math.ceil (-36.93); -36

Round to the nearest multiple

If you need to round a value to the nearest multiple of 5, create a function that divides the number by 5, rounds it, and then multiplies the result by the same value:

function roundTo5 (num) (return Math.round (num / 5) * 5;)

Using:

roundTo5 (11); \u003e 10

If you need JavaScript to round to two digits, you can pass both the seed and the multiplicity to the function:

function roundToMultiple (num, multiple) (return Math.round (num / multiple) * multiple;)

To use the function, include the number to be rounded and the multiplicity in its call:

var initialNumber \u003d 11; var multiple \u003d 10; roundToMultiple (initialNumber, multiple); \u003e 10;

To round values \u200b\u200bonly up or down, replace round with ceil or floor in the function.

Range Snap

Sometimes you need to get the value of x, which must be within a certain range. For example, we need a value between 1 and 100, but we get a value of 123. To fix this one can use min () ( returns the smallest of the numbers) and max ( returns the maximum number allowed).

Using:

var lowBound \u003d 1; var highBound \u003d 100; var numInput \u003d 123; var clamped \u003d Math.max (lowBound, Math.min (numInput, highBound)); console.log (clamped); \u003e 100;

You can create a function or extension of the Number class.

The Math.round () function returns the value of a number rounded to the nearest integer.

The source for this interactive example is stored in a GitHub repository. If you "d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

Math.round (x)

Parameters

x A number.

Return value

The value of the given number rounded to the nearest integer.

Description

If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of + ∞. Note that this differs from many languages \u200b\u200b"round () functions, which often round this case to the next integer away from zero , instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

Because round () is a static method of Math, you always use it as Math.round (), rather than as a method of a Math object you created (Math has no constructor).

Examples

Math.round (20.49); // 20 Math.round (20.5); // 21 Math.round (42); // 42 Math.round (-20.5); // -20 Math.round (-20.51); // -21

Demonstrative Implementation

Below is a snippet of code that is functionally equivelent to math.round except that the snippet of code below is slower than Math.round. The purpose of the snippet of code below is to demonstrate how Math.round works.

Function vanilla_round (x) (var y \u003d Math.abs (x) + 0.5; // so that less than 1/2 rounds down; greater rounds up return Math.floor (x + 0.5))

The modulus operator above gets the decimal part of x. Further, the above code snippet could be modified to round to a certain precision on a number:

Function round_to_precision (x, precision) (var y \u003d + x + (precision \u003d\u003d\u003d undefined? 0.5: precision / 2); return y - (y% (precision \u003d\u003d\u003d undefined? 1: + precision));)

Round_to_precision (11, 2); // outputs 12 round_to_precision (11, 3); // outputs 12 round_to_precision (11, 4); // outputs 12 round_to_precision (11, 5); // outputs 10 round_to_precision (11, 6); // outputs 12 round_to_precision (11, 7); // outputs 14 round_to_precision (11, 8); // outputs 8 round_to_precision (3.7, 0.5); // outputs 3.5 round_to_precision (3.75, 0.5); // outputs 4 round_to_precision (3.8, 0.5); // outputs 4

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.0.
ECMAScript 5.1 (ECMA-262)
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Math.round" in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of "Math.round" in that specification.
Draft

Browser compatibility

The compatibility table in this page is generated from structured data. If you "d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
roundChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

Now let's look at the floor method (translated as gender)which works the opposite of the ceil method, i.e. he rounds down a fractional number.

As you can see, the floor method rounded 35.97 down to 35, which is downward. Although 0.97 is greater than 0.5 (cm. ).

This lesson covered the methods of the Math object, allowing fractional decimal numbers to be rounded.

Now you need to do your homework.

Your task is to write a function that takes two parameters.
1. An array consisting of numbers with fractions.
2. Rounding method "round", "ceil" or "floor".

At the output, the function should output the same array, but all the elements of the array should be rounded using the Math object specified in the second parameter of the method.

Source array:

var numberArray \u003d;

At first, the solution to this problem may seem almost identical to the solutions to the household problems in the first three lessons of this topic. But not everything is so simple ...

Solution # 1 - Attention

By the condition of the problem the function must take two parameters - the original array and one of the methods: "round", "ceil" or "floor". Based on this, I tried to do so...

In this solution, we create a function with two parameters, and when we call it, we try to specify the original array and the NAME of one method as the function parameters:
decimal (numberArray, round) - in this case round.

But we will not get the result, since DO NOT specify a method NAME as a function parameter.

Pay attention: it is no coincidence that the names of the methods "round", "ceil" and "floor" in the problem statement enclosed in quotes.

decimal (numberArray, "round") - but this will not be correct either !!!

Solution # 2 - Correct the previous solution

You can solve the problem by specifying one parameter for the function.


35 - Rounded element


13 - Rounded element


17 - Rounded element


79 - Rounded element

Here we managed to achieve the desired result: the round method rounded all numbers in. But condition is not metsince the function only takes one parameter.

Solution # 3 - Function with two parameters

Here the problem is solved correctly. To do this, you had to remember the topic of conditions in javascript and apply several conditions at the same time.

34.82 - the original element of the array
35 - round up

12.9 - the original element of the array
13 - round up

17.01 - the original element of the array
18 - round up

78.51 - the original element of the array
79 - round up

it the right decision Homework. Here, for the function, two parameters are specified according to the condition.

Try on the last line of this solution:
decimal (numberArray, "ceil") as the second parameter of the function, specify the names of the other methods "round" and "floor" of the Math object.

Solution # 4 - Function with two parameters + prompt method

I decided to optimize the previous solution a bit and added a prompt method that calls a modal window containing a field for entering information.

Now, thanks to this, it will be possible to enter the name of one of the methods round, floor or ceil in the input field and get the corresponding result.

This is how the round, floor, or ceil methods of the Math object work, which round off fractional numbers.