Simple rounding rules in JavaScript. We study the methods and apply in practice. JavaScript - Party - TypeScript rounding Parsefloat JavaScript 2 Sign Sign

Hello. Today, in the JavaScript column, we will look at how to set on JavaScript the number of seasolines in the floating point numbers. For example, you need to leave 3 decimal sign when displaying, or only two.

Task: javascript number of semicolons

So, we are faced with the task: there is a result of calculations, in which there are numbers before the semicolons, and after the comma. Decimal. Suppose the result turned out this 1538.9891200153. But when the output should be the number reflecting the amount, where the amount of banknotes is up to the comma, and after - kopecks.

There are several ways to solve this task.

Solution 1: JavaScript Number of semicolons with the Tofixed method

tofixed is an embedded in JavaScript method that is applied to any number, the accuracy takes an accuracy rounding (that is, the number of seasitage characters).

Var num \u003d 1538.9891200153; num_str \u003d num.tofixed (); // num_str \u003d 1538; num_str \u003d num.tofixed (2); //Num_str\u003d1538.98; num_str \u003d num.tofixed (5); //Num_str\u003d1538.98912;

The accuracy parameter in this function should be at least 0 (does not take negative values), and not more than 20.

You can also do without a variable, for example, like this:

Num_str \u003d (1538.9891200153) .tofixed (2); //Num_str\u003d1538.98;

Solution 2: JavaScript Number of semicolons with the TopRecision method

This solution is based on the same built-in JavaScript method. A distinctive feature This method is that the parameter taken to the input indicates not accuracy (the number of decimal signs), but the total number of signs (both to the comma and after it).

Var num \u003d 1538.9891200153; num_str \u003d num.toprecision (5); //Num_str\u003d1538.9; num_str \u003d num.toprecision (7); //Num_str\u003d1538.989;

Solution without signs after a comma: javascript number of semicolons

If the decimal signs need to be completely folded, that is, it is necessary to round the fractional number to the whole, then you can use the functions of the Math: Round, Ceil and Floor.
Round - rounds in a large or smaller side (depending on the number). If the value after the semicolons is more than half, then rounds to the whole side, if less - to smaller. That is, if 0.51 - will be 1, if 0.49 - 0.

Ceil - from the English. The ceiling is always rounded into the biggest side.

Floor - from the English. Paul rounds always in a smaller side.

Var num \u003d 1538.9891200153; num_str \u003d math.round (num); // num_str \u003d 1539; num_str \u003d math.floor (NUM); // num_str \u003d 1538; num_str \u003d math.ceil (num); // num_str \u003d 1539;

That's all. I hope this note helped you solve the task. If something failed - ask questions using the green button "Ask a question by a specialist", or in the comments.



JavaScript-mathematics, rounding up to two decimal places (9)

I have the following JavaScript syntax:

Var Discount \u003d Math.round (100 - (Price / ListPrice) * 100);

This is rounded to an integer. How can I return the result with two decimal signs?

Here is a working example

VAR VALUE \u003d 200.2365455; Result \u003d Math.round (Value * 100) / 100 // Result Will BE 200.24

For processing rounding to any number of decimal places for most needs, there will be enough function with 2 code lines. Here is an example code for the game.

Var testnum \u003d 134.9567654; VAR Decpl \u003d 2; var testres \u003d roundDec (Testnum, Decpl); Alert (Testnum + "Rounded to" + Decpl + "Decimal Places IS" + Testres); FUNCTION ROUNDDEC (NBR, DEC_PLACES) (VAR MULT \u003d MATH.POW (10, DEC_PLACES); Return Math.round (NBR * MULT) / MULT;)

The best and simple solution I found is

Function Round (RETURN NUMBER (Math.round (Value + E "+ Decimals) +" E - "+ Decimals);) Round (1.005, 2); // 1.01

Small variation of the accepted answer. Tofixed (2) Returns the string, and you will always get two decimal signs. It can be zeros. If you want to suppress the final zero (s), just do it:

Var discount \u003d + ((Price / listPrice) .tofixed (2));

Edited: I just found that it seems an error in Firefox 35.0.1, which means that the above can give Nan some values.
I changed my code on

Var Discount \u003d Math.round (Price / ListPrice * 100) / 100;

This gives a number with an accuracy of two decimal places. If you need three, you will multiply and divide 1000, and so on.
Op wants two decimal discharge always, but if tofixed () is broken in Firefox, you first need to fix it.
See https://bugzilla.mozilla.org/show_bug.cgi?id\u003d1134388.

To get a result with two decimal signs, you can do the following:

Var discount \u003d math.round ((100 - (Price / ListPrice) * 100) * 100) / 100;

The value that needs to be rounded is multiplied by 100 to save the first two digits, then we divide to 100 to get the actual result.

I think that the best wayI saw it to multiply by 10 per number of numbers, then make math.round, and then finally divide 10 per number of numbers. Here is a simple function that I use in typewritten texts:

Function RoundToxDigits (Value: Number, Digits: Number) (Value \u003d Value * Math.pow (10, Digits); Value \u003d Math.round (Value); Value \u003d Value / Math.pow (10, Digits); Return Value; )

Or simple javascript:

Function RoundtoxDigits (Value, Digits) (IF (! Digits) (digits \u003d 2;) Value \u003d Value * Math.pow (10, Digits); Value \u003d Math.round (Value); Value \u003d Value / Math.pow (10 , digits); Return Value;)

NOTE. - See Edit 4 if 3-digit accuracy is important.

Var discount \u003d (Price / listPrice) .tofixed (2);

tofixed is rounded up or down for you depending on the values \u200b\u200bexceeding 2 decimal signs.

Change. As mentioned by others, it converts the result in the string. To avoid this:

Var discount \u003d + ((Price / listPrice) .tofixed (2));

Editing 2. - As mentioned in the comments, this function is not performed with some accuracy, for example, in the case of 1.005 it will return 1.00 instead of 1.01. If accuracy is important to such an extent, I found this answer: https: //.com/a/32605063/1726511 What seems to work well with all the tests that I tried.

One minor modification requires, but the response indicated above returns integers when it is rounded to one, therefore, for example, 99.004 will return 99 instead of 99.00, which is not perfect for price display.

Edit 3. - It seems that Tofixed on the actual return of Still twisted some numbers, it is final editing seems to work. GEEZ so many reparations!

Var discount \u003d roundto ((Price / ListPrice), 2); FUNCTION ROUNDTO (N, DIGITS) (IF (digits \u003d\u003d\u003d undefined) (digits \u003d 0;) var multiplicator \u003d math.pow (10, digits); n \u003d parsefloat ((n * multiplicator) .tofixed (11)); var test \u003d (math.round (n) / multiplicator); Return + (test.tofixed (digits));)

Edit 4. "You guys kill me." Edit 3 fails on negative numbers, without digging in why it is easier to simply make a negative number positive before making rounding, and then return it back before returning the result.

FUNCTION ROUNDTO (N, DIGITS) (var negative \u003d false; if (digits \u003d\u003d\u003d undefined) (digits \u003d 0;) if (n< 0) { negative = true; n = n * -1; } var multiplicator = Math.pow(10, digits); n = parseFloat((n * multiplicator).toFixed(11)); n = (Math.round(n) / multiplicator).toFixed(2); if(negative) { n = (n * -1).toFixed(2); } return n; }

The fastest way - faster than Tofixed ():

Two decaliles

x \u003d .123456 result \u003d math.round (x * 100) / 100 // Result .12

Three decimalities

x \u003d .123456 result \u003d math.round (x * 1000) / 1000 // result .123

Function Round (Num, DEC) (Num \u003d Math.round (NUM + E "+ DEC) RETURN NUMBER (NUM +" E - "+ DEC)) // Round to a Decimal of Your Choosing: Round (1.3453.2)

Hello, lovers javascript-a. You have already noticed that this language is very extraordinary and in each section stands out for its peculiarities and unusual technical solutions. Therefore, today's publication is dedicated to the topic: JavaScript rounding.

After reading the current article, you will find out why it is necessary to round the numbers, what methods and properties in JS perform this function, as well as the division of 0. Without changing your principles, I will attach examples to key points of the material and write out each action in detail. Now let's start learning!

Important notes about numbers

To begin with, remember that in JS all kinds of numbers (fractional and integer) refer to the type Number. In addition, all of them are 64-bit, as they are stored in the "Double Precision" format, which is also known under the IEEE-754 standard.

Created numerical variables with the usual way:

var numb \u003d 35; // natural number

var DROB \u003d 0.93; // decimal representation

var numb16 \u003d 0xFF; // 16-richery system

Supports other numeric views. So, you can also create numbers with a floating point (they are sometimes called "numbers in scientific format").

In appeared support for a very interesting method tOLOCALESTRING ()which formats all numeric parameters according to specifications prescribed in ECMA 402. Due to this large numbers, phone numbers, currencies and even percentages are beautifully displayed in the dialog box.

var num \u003d 714000.80;

alert (num.tolocalestring ());

To work with elements of type Number, a whole global object with a bunch of all sorts of mathematical functions, whose name Math..

In addition, there are other methods that perform rounding numerical values \u200b\u200bto integers, up to tenths, hundredths, etc. Consider them all more.

Great and Mighty Math

The global Math object includes a huge number of various mathematical and trigonometric functions. This is a very necessary object and often cuts the developers when working with digital data.

On other platforms, there are analogies Math. For example, in popular languages \u200b\u200bsuch as Java and C #, Math is a class that supports all the same standard functions. So, as you see this tool is really great and mighty.

Now I want to go through the specific methods responsible for rounding, and tell about them in detail.

Math.floor ()

I will start S. Math.floor. Pay attention to the name of the method. It logically it becomes clear that since we are talking about rounding, and the literal translation of the word "Floor" means "floor", then this tool rounds the processed values \u200b\u200binto a smaller straight.

An option is also possible when the processed number using this function remains the same. All because rounding is carried out on non-neural inequality (<=). Таким образом, при отработке этой строчки кода:

alert (math.floor (4.5));

the answer will be the number 4.

Math.ceil ()

Again, look at the name (in such a method, the material is quickly absorbed). If someone does not know, "Ceil" means "ceiling". It means that rounding the numeric data will be carried out in the most side, using a non-inequality (\u003e \u003d).

alert (math.ceil (4.5));

As you already guessed, the response will be the number 5.

Math.round ()

This method rounds fractional number to the nearest whole. So, if the fractional part is in the range from 0 and to 0.5 not inclusive, the rounding occurs to a smaller value. And if the fractional part is in the range from inclusive 0.5 and until the next integer, it is rounded to a greater whole.

alert (math.round (4.5));

I hope everyone thought or told the correct answer - 5.

Some more methods

JavaScript also has other 2 methods that are engaged in rounding numerical representations. However, they are somewhat different.

It will be about such instruments as tofixed () and tOPRECISION (). They answer not just for rounding, but for its accuracy to certain signs. Let's fight deeper.

tofixed ()

With this mechanism, you can specify, to how many signs after the comma need to round the value. The method returns the result as a string. Below I attached an option with three different options. Analyze the answers received.

var num \u003d 5656.9393;

document.Writeln (num.tofixed ()); // 5657.

document.Writeln (num.tofixed (2)); // 5656.94

document.Writeln (num.tofixed (7)); // 5656.9393000

As can be seen, if you do not specify the argument, then Tofixed ()) rounds fractional value to whole numbers. In the third line completed rounding up to 2 charactersand in the fourth - because of the parameter "7", three more 0 were addressed.

tOPRECISION ()

This method acts somewhat differently. At the place of the argument, you can leave both an empty place and set the parameter. However, the latter will round the numbers before the specified number of numbers, not paying attention to the comma. Here are the results of the program rewritten from the past of Example:

var num \u003d 5656.9393;

document.Writeln (num.toprecision ()); // 5656.9393

document.Writeln (Num.TopRecision (2)); // 5.7E + 3

document.Writeln (num.toprecision (7)); // 5656.939

File of division at 0 in js

As is known from lessons in mathematics, it is impossible to divide to zero. This rule took as a basis most of the creators of programming languages. Therefore, when dividing to zero, all programs give an error.

However, JavaScript distinguished himself here. So, during the execution of such an operation, no bug messages arise ... because such an operation returns "Infinity"!

Why so? As is known from the same mathematical sciences, the smaller the divider, the result is a greater number. That is why the creators of this prototype-oriented language decided to abandon the templates and go their own way.

For those who are first faced with the Infinity value, below I explained its features.

Infinity - means infinity and fully matches the mathematical sign ∞.

May be negative. All standard rules for working with arithmetic operators are also saved.

alert (12/0); // Infinity

alert (12.34 / 0); // Infinity.

alert (-3 / 0); // -INFINITY.

On this, perhaps, and finish. If you like the publication, then be sure to subscribe to my blog. Do not gread a reference to interesting articles and share them with friends. Bye Bye!

In this article, consider in detail the numbers, mathematical operators, methods of transformation of the number in the string and vice versa, as well as many other important points.

Isfinite function

The ISFinite feature allows you to check whether the argument is a finite number.

As a response this feature Returns false if the argument is infinity, -infinity, Nan or will be shown to one of these special numeric values. Otherwise, this function will return the value of True.

Isfinite (73); // True Isfinite (-1/0); // False Isfinite (Infinity); // False Isfinite (NAN); // False Isfinite ("Text"); // False

In addition to the global iSFinite function in JavaScript there is another Number.isfinite method. In contrast to ISFinite, it does not carry out forced argument to the number.

Isfinite ("73"); // True Number.isfinite ("73"); // False

Isnan feature

The ISNAN function is designed to determine whether the argument is a number or can be transformed to it. If so, the ISNAN function returns False. Otherwise, it returns True.

ISNAN (NAN); // True Isnan ("25px"); // True, because 20px is not an iSnan number (25.5); // False Isnan ("25.5"); // False Isnan (""); // False, because The space or not only spaces is converted to 0 ISNAN (NULL); // False, because NULL value is converted to 0 ISNAN (TRUE); // False, because True value is converted to 1 ISNAN (FALSE); // False, because False value is converted to 0

If this action needs to be done without bringing the type, then use the Number.isnan method. This method was introduced into the language, starting with ECMAScript 6.

How to explicitly convert a row to the number?

It is clearly brought by a row to the number by the following ways:

1. Use unary operator +.which must be placed before the value.

+ "7.35"; // 7.35 + "Text"; // Nan.

This method neglects spaces at the beginning and end of the string, as well as \\ n (row translation).

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

Using this method, it is necessary to pay attention to the fact that an empty line or a string consisting of spaces and \\ n is translated into the number 0. In addition, it also converts the data type NULL and logic values to the number.

Null; // 0 + True; // 1 + false; // 0 + ""; // 0.

2. PARSEINT function. This feature is intended for conversion. argument for an integer. In contrast to use unary operator +., this method allows you to convert a string to a number in which not all characters are digital. It begins to convert the string starting from the first symbol. And as soon as it encounters a symbol that is not digital, this feature stops its operation and returns the resulting number.

Parseint ("18px"); // 18 PARSEINT ("33.3%"); // 33.

This feature can work with different systems Number (binary, octal, decimal, hexadecimal). Note The base of the number system is carried out by means of 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 in JavaScript, there is 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. PARSEFLOAT function. The ParseFloat feature is similar to Parseint, except for the transformation of the argument to fractional number.

PARSEFLOAT ("33.3%"); //33.3.

In addition, the ParseFloat feature, unlike Parseint, does not have 2 arguments, and therefore it always tries to consider the string as a number in the decimal number system.

PARSEFLOAT ("3.14"); PARSEFLOAT ("314E-2"); PARSEFLOAT ("0.0314E + 2");

In addition to the PARSEFLOAT function in JavaScript, there is a Number.ParseFloat method. This method is no different from the PARSEFLOAT function and was introduced in JavaScript with the ECMAScript 2015 specification (6).

Transformation of the number in the string

You can turn the number in the string using the TOSTRING method.

(12.8) .tostring (); //"12.8 "

The Tostring method also allows you to specify the foundation of the number system with which it is necessary to explicitly bring the number to the row:

(255) .tostring (16); // "FF"

How to check whether a variable number

To determine whether the value variable can be variable using one of the following methods:

1. Using ISNAN and ISFINITE functions:

// MyVar - Variable if (! ISNAN (Parsefloat (MyVar)) && iSfinite (ParseFloat (MyVar)) (// MyVar is a number or can be given to it);

In the form of a function:

// Function Isnumeric (Return! ISNAN (PARSEFLOAT (VALUE)) && ISFINITE (PARSEFLOAT (VALUE));) // Using Var MyVar \u003d "12px"; Console.log (ISNUMERIC (MyVar)); // True.

This method allows you to determine whether the specified value is or can be given to it. This option does not consider an empty string, a string of spaces, a value , infinity, -infinity, true and false.

2. Using the TypeOf operator and ISFinite functions, Isnan:

// A function that checks whether the value is the number of 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 feature determines whether the specified value is the type of Number, and whether it does not belong to one of the special infinity, -infinity and Nan values. Esley is so, then this function returns True.

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

Number.isinteger ("20"); // False, because This method does not translate string to the number of Number.isinteger (20); // True, because This value is the number

Even and odd numbers

Check whether the number is used or odd by the following functions:

// Function for checking the number to read function iSeven (N) (RETURN N% 2 \u003d\u003d 0;) // Function for checking the number to infirmity FUNCTION ISODD (N) (Return Math.abs (N% 2) \u003d\u003d 1; )

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

Value \u003d 20; If (Number.isinteger (Value)) (IF (ISEVEN (VALUE)) (Console.LOG ("Number" + Value.Tostring () + "- Thin");))

Simple numbers in JavaScript

Consider an example in which the simple numbers from 2 to 100 with JavaScript are removed.

// Function that checks whether the number is simple 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 Number in JavaScript

Round out a fractional number to the whole value in JavaScript in various ways.

1. Using Math.floor, Math.ceil and Math.round methods specifically designed for this. MATH.FLOOR method rounds fractional number to the nearest whole down, i.e. Simply discard the fractional part. Math.ceil curls a fractional number to the nearest whole up. Math.round rounds the 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 tweaking is carried out.

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

2. Using the Tofixed method. This method rounds the fractional part of the number to a given accuracy. The result of rounding returns as a string.

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

If the signs after the comma for the formation of the specified accuracy of the number lacks, it is complemented by zeros.

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

3. Through the TopRecision method. This method represents a number with the indicated accuracy. At the same time, it can round up not only fractional, but also a whole part of the number. The obtained number, this method can be represented depending on the result with a fixed comma 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 logic operators not or or.

// by double logical denial Console.log (~~ 7.9); // 7 // Through the use of logical or with zero: Console.log (7.9 ^ 0); // 7.

Whole and fractional part of the number

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

Console.log (Math.floor (7.21)); // 7 Console.log (Parseint (7.21)); // 7.

You can get a fractional part of the number you can use the percentage operator (%). This operator returns the residue that will be obtained from dividing the first number to the second. In this case, it is necessary to use 1 as 2 numbers.

Console.log (7.21% 1); // 0.20999999999999996 // With an accuracy of 2 characters after the semicolon Console.log ((7.21% 1) .tofixed (2)); // "0.21"

In addition, the fractional part can also be obtained by computing:

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

Whether the number is divided by

To determine whether the number of aims can be found using the percent operator:

Var number \u003d 9; // If the residue from the division of the number of Number 3 is 0, then yes, otherwise there is no if (Number% 3 \u003d\u003d 0) (Console.log ("Number" + Number + "is divided into 3");) ELSE (CONSOLE. Log ("The number" + Number + "is not divided into 3");)

Formatting numbers

In JavaScript, format the output output in accordance with regional standards (operating system language settings) allows the TOLOCALESTRING () method.

For example, perform the formatting of the number in accordance with the regional standards that are installed in the default system:

Var number \u003d 345.46; Console.log (Number.tolocalestring ()); // "345.46"

For example, we will perform the formatting of 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 in the form of 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 €"

Pose of interest in the form of interest:

Console.log ((0.45) .tolocalestring ("RU-RU", (Style: "Percent"))); // "45%"

Clear the number on the discharge (USEGROUPING property):

Console.log ((125452.32) .Tolocalestring ("RU-RU", (Usegrouping: True))); // "125 452,32"

Display with a certain number of digits (2) after the comma:

Console.log ((1240.4564) .Tolocalestring ("RU-RU", (MinimumFractionDigits: 2, MaximumFractionDigits: 2))); // "1 240.46"

Comparison of numbers

To compare the numbers in JavaScript, the following operators are used: \u003d\u003d (equal) ,! \u003d (not equal),\u003e (more),< (меньше), >\u003d (more or equal),<= (меньше или равно).

For example, we compare two numbers:

Console.log (2\u003e 3); // False Console.log (5\u003e \u003d 3); // True.

When comparing numbers with a fractional part, it is necessary to consider the errors that may occur during these calculations.

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

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

The errors occur because all the calculations of the computer or other electronic device produces in 2 number system. Those. Before performing some actions, the computer must first convert the number in the expression in 2 of the number system. But, not any fractional decimal number can be represented in 2 number system for sure.

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

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 definite accuracy:

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 comparison results. Those. It turns out that actually javascript will be seen this entry as follows:

0.6000000000000001==0.6

When calculating or mapping numbers with a fractional part, you should always indicate the accuracy with which it must be done.

For example, compare numbers up to 2 decimal places using Tofixed () and TOPRECISION () methods:

// Tofixed () method Console.log ((0.2 + 0.4) .tofixed (2) \u003d\u003d (0.6) .tofixed (2)); // True // TopRecision () method Console.log ((0.2 + 0.4) .toprecision (2) \u003d\u003d (0.6) .toprecision (2)); // True.

Major mathematical operations

JavaScript exists the following mathematical operators: + (addition), - (subtraction), * (multiplication), / (division),% (residue from division), ++ (zoom to 1), - (reduce value to 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 OST (0) 5% 2 // 1, i.e. 5: 2 \u003d 2 (.5) \u003d\u003e 5-2 * 2 \u003d\u003e OST (1) 7.3% 2 //1.3, i.e. 7.3: 2 \u003d 3 (.65) \u003d\u003e 7.3-2 * 3 \u003d\u003e Ost (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 OST (1.5) -9% -2.5 //-1.5, i.e. 9: 2.5 \u003d 3 (.6) \u003d\u003e 9-2.5 * 3 \u003d\u003e OST (1.5) -2% 5 // - 2, i.e. 2: 5 \u003d 0 (.4) \u003d\u003e 2-5 * 0 \u003d\u003e OST (2) x \u003d 3; Console.log (X ++); // displays 3, already already sets 4 Console.log (x); // 4 x \u003d 3; Console.log (++ x); // Sets 4 and displays x \u003d 5; Console.log (X--); // displays 5, already then sets 4 Console.log (x); // 4 x \u003d 5; Console.log (- X); // Sets 4 and displays the combined operators in JavaScript in addition: 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.

Very often calculations in JavaScript give not quite the results that we want. Of course, we can do with numbers anything - rounding in a large or smaller side, set the ranges, cut off unnecessary numbers to a certain number of decimal places, it all depends on what you want to do in the future with this number.

Why do you need rounding?

One of the curious aspects of JavaScript is that it actually does not store integers, we immediately work with floating point numbers. This, in combination with the fact that many fractional values \u200b\u200bcannot be expressed by the final number of decimal signs, we can get such results in JavaScript:

0.1 * 0.2; > 0.020000000000000004 0.3 - 0.1 > 0.19999999999999998
For practical purposes, this inaccuracy does not matter, in our case we are talking about error in quintillion dollars, however, someone can disappoint. We can get a slightly strange result and when working with numbers that are valve values, percent or file sizes. In order to correct these inaccuracies, we just need to be able to round the results, while it is enough to establish decimal accuracy.

The rounding of the numbers has practical application, we can manipulate the 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

In order to cut off the decimal number, use the TOFIXED or TopRecision method. Both are taken by a single argument that determines, respectively, how many meaningful numbers (i.e., the total number of numbers used among the number) or after a semicolon (quantity after the decimal point) should include the result:
  1. If the argument is not defined for Tofixed (), then by default it will be zero, which means 0 marks after the comma, the argument has a maximum value equal to 20.
  2. If the argument is not specified for TopRecision, the number remains 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 () methods return a string representation of the result, not a number. This means that when summing the rounded value with Randnum, rows concatenate will be made, and not the amount of 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, you will need to apply ParseFloat:

Let Randnum \u003d 6.25; Let Rounded \u003d ParseFloat (Randnum.tofixed (1)); Console.log (Rounded); \u003e 6.3.
Please note that 5 values \u200b\u200bare rounded, with the exception of rare cases.

Tofixed () and TopRecision () methods are useful, because they can not only cut off the fractional part, but also complement the signs after the comma, which is convenient when working with currency:

Let Wholenum \u003d 1 Let Dollarscents \u003d Wholenum.Tofixed (2); Console.log (Dollarscents); \u003e "1.00"
Condition Note that TopRecision will give the result in an exponential record if the number of integers is larger than the accuracy 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 to a smaller side, and in a large:

Let numtest \u003d 1.005; numtest.tofixed (2); \u003e "1.00"
The result of the calculation above was to be 1.01, and not 1. If you want to avoid a similar error, we can use the solution proposed by Jack L Moore, which uses exponential numbers to calculate:

FUNCTION ROUND (RETURN NUMBER (MATH.ROUND (VALUE + E "+ Decimals) +" E - "+ Decimals);)
Now:

Round (1.005.2); \u003e 1.01
If you want a more reliable solution than the solution shown above, you can go to MDN.

Machine Epsilon rounding

The alternative method of rounding decimal numbers was introduced into the ES6. Machine Epsilon Rounding provides a reasonable error limit when comparing two floating point numbers. Without rounding, comparisons can give results like as follows:

0.1 + 0.2 \u003d\u003d\u003d 0.3\u003e False
We use Math.epsilon in our 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: the first - current calculation, the second is the expected result. It returns a comparison of two:

EPSEQU (0.1 + 0.2, 0.3)\u003e True
All modern browsers are already supporting ES6 mathematical functions, but if you want to get support in browsers such as IE 11, use PolyFills.

Cutting down fractional part

All methods presented above are able to round up to decimal numbers. In order to simply cut off the number up to two signs after the comma, you must first multiply it by 100, and then the result obtained is already divided by 100:

FUNCTION TRUNCATED (NUM) (RETURN MATH.TRUNC (NUM * 100) / 100;) Truncated (3.1416)\u003e 3.14
If you want to adapt the method for any number of semicolons, you can use a double bitty denial:

FUNCTION TRUNCATED (LET NUMPOWERCONVERTER \u003d MATH.POW (10, DECIMALPLACES); RETURN ~~ (NUMPOWERCONVERTER) / NUMPowerConverter;)
Now:

Let Randint \u003d 35.874993; Truncated (Randint, 3); \u003e 35.874.

Rounding to the nearest number

In order to round the decimal number to the nearest number in more or in a smaller side, depending on what we are closest to, use math.round ():

Math.round (4.3)\u003e 4 Math.round (4.5)\u003e 5
Please note that "half of the value", 0.5 is rounded in a large direction according to the rules of mathematics.

Rounding to a smaller to the nearest integer

If you want to always round down at a smaller side, use Math.Floor:

Math.floor (42.23); \u003e 42 math.floor (36.93); \u003e 36.
Please note that rounding in a smaller side works for all numbers, including for negative. Imagine a skyscraper with an infinite number of floors, including the low-level floors (representing negative numbers). If you are in the elevator at the lower level between 2 and 3 (which is a value -2.5), Math.floor will deliver you to -3:

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

Math.trunc (-41.43); \u003e -41
You will find Polyfill on MDN to provide Math.trunc support in browsers and IE / EDGE.

Rounding to more to the nearest integer

On the other hand, if you always need to round up to the biggest, use Math.ceil. Again, remember the endless elevator: math.ceil will always go up, no matter 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 to a larger / smaller number

If we want to round up to the nearest number, multiple 5, the easiest way to create a function that divides the number on 5 rounds it, and then multiplies it to the same amount:

FUNCTION ROUNDTO5 (NUM) (Return Math.round (NUM / 5) * 5;)
Now:

RoundTo5 (11); \u003e 10.
If you want to round up to multiple your value, we use a more general function by passing the initial value and multiple to it:

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 the number in the range

There are many cases when we want to get the value of x lying within the range. For example, we may need a value from 1 to 100, but at the same time we received a value of 123. In order to fix it, we can use the minimum (returns the smallest of the number of numbers) and the maximum (returns the largest of any multiple numbers). In our example, the range from 1 to 100:

Let LowBound \u003d 1; Let highbound \u003d 100; Let Numinput \u003d 123; Let Clamped \u003d Math.Max \u200b\u200b(Lowbound, Math.min (Numinput, Highbound)); Console.log (clamped); \u003e 100;
Again, we can re-use the operation and wrap it all into the function, we use the solution proposed 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 a bank rounding, is that rounding for this case occurs to the nearest black. This rounding method works without a statistical error. The best solution was proposed by Tim Down:

Function Gaussround (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 sign in CSS:

Since JavaScript is often used to create a positional conversion of HTML elements, you can wonder what happens if we generate decimal values \u200b\u200bfor our items:

#Box (Width: 63.667731993px;)
Good news is that modern browsers will take into account decimal values \u200b\u200bin a block model, including in percentage or pixel units of measurement.

Sorting

Very often, we have to sort any elements, for example, we have an array of gaming records, while they should be organized as descending order of players. Unfortunately, the standard Sort () method has some amazing restrictions: it works well with frequently used English words, but immediately breaks at a meeting with numbers, unique characters or words in the upper case.

Sort in alphabetical order

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

Let Fruit \u003d ["Butternut Squash", "Apricot", "Cantaloupe"]; fruit.sort (); \u003e "Apricot", "Butternut Squash", "Cantaloupe"]
Nevertheless, we are confronted with the problem as soon as one of the elements is in the upper case:

Let Fruit \u003d ["Butternut Squash", "Aprot", "Cantalope"]; fruit.sort (); \u003e "Cantaloupe", "Aprot", "Butternut Squash"]
This is due to the fact that, by default, the sorter compares the first symbol presented in Unicode. Unicode is unique code For any symbol, regardless of the platform, regardless of the program, regardless of the language. For example, if you look through the code table, the "A" character is u + 0061 (in hexadecimal system 0x61), while the symbol "C" has code U + 0043 (0x43), which goes before in the Unicode table than the symbol "A".

To sort an array that can contain mixed registers of the first letters, we need to either convert all items to temporarily into the lower register, or determine your sorting 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) (RETURN A.LOCALECOMPARE (B, EN ", (" SENSITITIVITY ":" BASE "));));) Let Fruit \u003d [" Butternut Squash "," apricot "," cantaloupe "]; AlphaSort (Fruit)\u003e
If you want to get an array sorted into the reverse alphabetical order, simply change the positions a and b to the function:

FUNCTION ALPHASORT (ARR) (RETURN B.LOCALECOMPARE (A, EN ", (" SENSITITIVITY ":" BASE "));));) Let Fruit \u003d [" Butternut Squash "," apricot "," cantaloupe "]; AlphaSort (Fruit)\u003e ["Cantaloupe", "Butternut Squash", "apricot"]
It is worth paying attention to that LocalecomPare is used with arguments, it is still necessary to remember that it is supported by IE11 +, for older IE versions, we can use it without arguments, and in the lower register:

FUNCTION CASESORT (ARR) (RETURN A.TOLOWERCASE (). LocalecomPare (B.TolowerCase ());));) Let Fruit \u003d ["Butternut Squash", "Apricot", "Cantaloupe"]; CaseSort\u003e [Apricot, "Butternut Squash", "Cantaloupe"]

Numerical sorting

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

Let highscores \u003d; highscores.sort (); \u003e
The fact is that the SORT () method produces a lexicographic comparison: and this means that the numbers will be converted to a string and comparisons will be carried out again by mapping the first character of this string in the Unicode Table Symbols. Therefore, we need to determine your sort order:

Let highscores \u003d; Highscores.sort (Return A - B;)); \u003e
Again, to sort numbers in the reverse order, change the positions a and b to the function.

Sort JSON-like structure

And 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 the arrow functions:

Scores.sort ((a, b) \u003d\u003e b.score - a.score));
For old browsers who do not have such support:

Scores.sort (Return a.score - B.Score));
As you can see, sorting in JavaScript is a pretty obvious thing, I hope that these examples will make it easy for life.

Work with power functions

The exercise is an operation, originally defined as a result of multiple multiplication of a natural number on itself, a square root of number A is a number given to a square. With these functions, we could enjoy constantly in everyday life in mathematics lessons, including when calculating areas, volumes or even physical modeling.

In JavaScript, a power function is represented as Math.pow (), in the new ES7 standard, a new exercise operator was presented to the degree - "* *".

Erend into degree

In order to build a number in the N-Uy degree, use the Math.POW () function, where the first argument is the number that will be erected into a degree, the second argument is an indicator of the degree:

Math.pow (3.2)\u003e 9
Such a form of recording means 3 in a square, or 3 × 3, which results in a result 9. Another example can be given, of course:

Math.pow (5.3); \u003e 125.
That is, 5 in Cuba, or 5 × 5 × 5, equal to 125.

ECMAScript 7 is the following version of JavaScript, in principle, we can use the new proposed exercise operator to a degree - * *, such a form of recording can be more visual:

3 ** 2 > 9
On the this moment Support for this operator is quite limited, so it is not recommended to use it.

The powerful function can be useful in various situations. A simple example, calculating the number of seconds in an hour: math.pow (60.2).

Square and cubic root

Math.SQRT () and Math.cbrT () are opposite to the math.pow () functions. As we remember, the square root of the number A is a number that gives A when the square is erected.

Math.SQRT (9)\u003e 3
At the same time, the cubic root of the number A is a number that gives a when the cube is erected.

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

Examples

Of course, we can use and not integer in one of these functions:

Math.pow (1.25, 2); \u003e 1.5625 Math.cbrT (56.57)\u003e 3.8387991760286138
Please note that it works quite well when using negative values \u200b\u200bof arguments:

Math.pow (-5.2)\u003e 25 Math.pow (10, -2)\u003e 0.01
However, for a square root it will not work:

Math.SQRT (-9)\u003e Nan
From mathematical analysis, we know that under imaginary number they understand square roots from negative numbers. And this can lead us to another technique of working with complex numbers, but this is another story.

You can use fractional values \u200b\u200bin math.pow () to find square and cubic roots numbers. Square root uses an indicator 0.5:

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

Math.pow (2.23606797749979,2)\u003e 5.0000000000001
In such situations, you will have to resort to cut-off signs in numbers or rounding to any value.

Some, for incomprehensible reasons in JavaScript confuse the Math.pow () function with Math.exp (), which is an exponential function for numbers as a whole. Note: B. english language The "indicator of the degree" is translated as "EXPONENT", therefore it is rather related to English-speaking, although there are also alternative indicator names such as Index, Power.

Mathematical constants

Working with mathematics in JavaScript is facilitated by a number of built-in constants. These constants are the properties of the Math object. It is worth noting that the constants are written in the upper case, and not Camelcase notation.

Math.abs, Parseint, ParseFloat

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

Math.abs ()

Math.abs () method Returns the absolute value of the number, which reminds us the same mathematical function of the number a.

Let newval \u003d -57.64; Math.abs (Newval); \u003e 57.64
Math.abs (0) always returns zero, but if you put a minus sign before the -math.abs function (NUM) we will always be a negative value.

Math.abs (0); \u003e -0

parseint ()

We know that JavaScript understands that "15" is a string, and not a number and, for example, when parsing CSS properties with JavaScript with any value from an unprepared array, our results can be unpredictable. We could get on the entrance line represented as "17px", and for us it is not rare. The question is how to convert this string in the actual value and use it in further calculations.

Syntax: Parseint (String, Radix);

The Parseint feature converts the first argument transmitted to it into a string type, interprets it and returns an integer or Nan value. Result (if not NAN) is an integer and represents the first argument (String), which is considered as a number in specified system Number (RADIX). For example, the base 10 indicates a conversion from decimal number, 8 - octal, 16 - hexadecimal and so on. If the base is greater than 10, then letters are used to designate numbers more than 9. For example, for hexadecimal numbers (base 16), letters from A to F.

Consider an example of working with CSS properties, where, conventionally 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\u200bon spaces:

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

Let Centerx \u003d Parseint (CENTERS, 10); \u003e 454 Let Centery \u003d Parseint (CENTERS, 10); \u003e 2087.
As you can see, we specify the number of the number to which the number will be converted to which this parameter is optional, but it is recommended to use it, in case you do not know which line will go to the input.

parseFloat ()

From the example above, you probably noticed that Parseint discards the fractional part. In our case, ParseFloat can work with floating point numbers. Again, it can be useful when parsing CSS and other tasks, especially when working with a floating point in percent.

Syntax: ParseFloat (String)

Let Fp \u003d "33.33333%"; Console.log (Parsefloat (FP)); \u003e 33.33333
Please note that there is no second argument in PARSEFLOAT syntax.

We understand that Parseint () and ParsEfloat () are extremely useful featuresIt is important to take into account that and there is no mistake without errors, so you need to check the range of expected values \u200b\u200band ultimately analyze the result to ensure that the values \u200b\u200bare correct.
Send anonymously


Top.