JavaScript rounding up to tenths. Simple rounding rules in JavaScript. We study the methods and apply in practice. Rounding up to the nearest integer

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!

Often the calculations give results that do not correspond to the limits of the desired ranges. As a result, you need to exercise JavaScript rounding up to a certain value.

Why round numbers?

JavaScript does not store integers, since their values \u200b\u200bare presented in the form of a floating point numbers. Many fractions cannot be represented by a number with a certain finite number of semicolons, so JavaScript can generate results, like the following:

0.1 * 0.2; > 0.020000000000000004

In practice, it will not have any importance, since it comes to the error in 2 quinylonne. But this may affect the result when working with numbers that represent valve values, percent or file size. Therefore, you need to do or up to a certain decimal sign.

Rounding decimal numbers

To "trim" a decimal number, Tofixed () or TopRecision () methods are used. They both take one argument that determines the number of significant and marks after the comma, which must be included in the result:

  • if for Tofixed () the argument is not defined, the default value is 0, that is, no signs after the comma; The maximum value of the argument is 20;
  • if for TopRecision () the argument is not specified, the number does not change.

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

And TOFIXED (), and TOPRECISION Return a rounded lower case representation, and not a number. This means that adding a rounted to RANDNUM will result in a concontine string, and not one number:

console.log (Randnum + Rounded); \u003e "6.256"

If you need to get a JavaScript rounding to the hundredths, 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 a large number of semicolons. It is convenient when working with numbers representing monetary units:

var wholenum \u003d 1 var dollarscents \u003d wholenum.tofixed (2); Console.log (Dollarscents); \u003e "1.00"

Please note that if there are more signs than the accuracy parameter specified, TopRecision will issue a result in a scientific format:

var num \u003d 123.435 Num.TopRecision (2); \u003e "1.2E + 2"

How to avoid mistakes when rounding decimal fractions

In some cases, Tofixed and TopRecision is carried out JavaScript rounding 5 to a smaller side, not up to more:

var numtest \u003d 1.005; numtest.tofixed (2); \u003e 1;

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

fUNCTION ROUND (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 on MDN..

Rounding with Epsilon

Alternative method JavaScript rounding up to tenths was introduced in ES6 ( also known as JavaScript 2015). « Machine Epsilon»Provides a reasonable error limit when comparing two floating semicolons. Without rounding, comparisons can give results like as follows:

0.1 + 0.2 \u003d\u003d\u003d 0.3\u003e False

Math.epsilon can be used in the function to obtain a correct comparison:

fUNCTION EPSEQU (X, Y) (RETURN MATH.ABS (X - Y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }

Function takes two arguments: One contains calculations, the second 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 mathematical functions. But if you need to provide support in old browsers, you need to use polyfilla.

Truncation of decimal numbers

All methods presented earlier perform JavaScript rounding up to tenths. To trim a positive number of up to two places after the comma, multiply it to 100, trough again, and then the result obtained is divided by 100, you need:

fUNCTION TRUNCATED (NUM) (RETURN MATH.TRUNC (NUM * 100) / 100;) Truncated (3.1416)\u003e 3.14

If something more flexible is required, you can use the broken operator:

fUNCTION TRUNCATED (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 implement Javascript rounding to the whole, Math.round () is used:

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

Note that " half values", Such as .5, rounded up.

Rounding down to the nearest integer

If you want to round down in a smaller side, 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 for negative. This can be represented as a skyscraper with an infinite number of floors, including below the foundation level ( representing negative numbers). If you are in the elevator between the basement floors 2 and 3 ( what matches the value -2.5), Math.floor will deliver you to the floor -3:

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

If you want to avoid this, use JavaScript Math rounding using Math.trunc () supported in all modern browsers (except IE / EDGE):

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

MDN also provides polyfill of three lines to provide Math.trunc support in old browsers and IE / Edge.

Rounding up to the nearest integer

If you want to round down decimal numbers up, use Math.ceil. The action of this method can also be represented as an endless elevator: math.ceil is always lucky "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

Rounding to the nearest multiple number

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

fUNCTION ROUNDTO5 (NUM) (Return Math.round (NUM / 5) * 5;)

Using:

roundTo5 (11); \u003e 10.

If you want to execute JavaScript rounding up to two characters, you can transmit functions as the initial number and multiplicity:

function RoundTomultiple (Num, Multiple) (Return Math.round (Num / Multiple) * Multiple;)

To use the function, turn on the rounded number and multiplicity in its call:

var initialnumber \u003d 11; var multiple \u003d 10; RoundTomultiple (InitialNumber, Multiple); \u003e 10;

To round the values \u200b\u200bonly in a large or smaller direction, replace in the Round function on Ceil or Floor.

Binding to range

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

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 class Number.

Their Math.round () FUNCTION RETURNS THE VALUE OF A NUMBER ROUNED 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 ROUNED 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 A 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 tat 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) (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

Desktop.MobileServer
Chrome.Edge.Firefox.Internet Explorer.Opera.Safari.Android WebView.Chrome for AndroidFirefox for AndroidOpera for AndroidSafari on ios.Samsung internetNode.js.
Round.Chrome 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

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 an answer, this function 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 string or a string consisting of spaces and \\ n is translated into the number 0. In addition, it also converts the NULL data type and logical values \u200b\u200bto 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 number systems (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 specified 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.

Now consider the Floor method (Translated - Paul)which works oppositely the CEIL method, i.e. is he rounded fractional number in smaller.

As you can see, the Floor method rounded the number 35.97 to 35, that is, in a smaller side. Despite the fact that 0.97 more 0.5 (cm. ).

In this lesson, Math object methods were considered, allowing rounded fractional decimal numbers.

Now you need to perform your homework.

Your task to write a feature 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 must be rounded using the MATH object specified in the second parameter.

Source array:

var numberarray \u003d;

First, the solution of this task may seem almost identical to the solutions of homework from the first three lessons of this topic. But not everything is so simple ...

SOLUTION №1 - ATTENTION

Under the condition of the task function must take two parameters - Source array and one of the methods: "Round", "Ceil" or "Floor". Based on this, I i tried to do this...

In this solution, create a function with two parameters, and when it is called, then you try to specify the source array as parameters of the function parameters and the name of one methods:
dECIMAL (NUMBERRAY, ROUND) - in this case Round.

But we will not get the result, since You can not specify the name of the method as the function parameter.

Note: After all, it is not by chance that the problem of the name "Round", "Ceil" and "Floor" enclosed in quotes.

decimal (NUMBERRAY, "ROUND") - but such a record will not be true either !!!

Decision # 2 - Correct the previous decision

You can solve the task, specifying one parameter for the function.


35 - Rounded Element


13 - rounded element


17 - rounded element


79 - rounded element

Here it was possible to achieve the desired result: the Round method rounded all the numbers. But the condition is not fulfilledSince the function takes only one parameter.

Decision number 3 - Function with two parameters

Here the task is solved correctly. To do this, it was necessary to remember the topic of conditions in JavaScript and apply several conditions at the same time.

34.82 - the source element of the array
35 - round in the big face

12.9 - The original element of the array
13 - round into the biggest

17.01 - the source element of the array
18 - round in the big face

78.51 - The original element of the array
79 - round into the biggest

it correct solution Homework. Here, two parameters are specified for the function according to the condition.

Try in the last row of this solution:
decimal (NUMBERRAY, "CEIL") As the second parameter of the function, specify the names of other "Round" and "Floor" objects of the MATH object.

Solution №4 - Function with two parameters + Prompt method

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

Now, thanks to this, you can enter the name of one of the Round, Floor or CEIL methods in the input field and get the corresponding result.

This is how the methods of the Round, Floor or CEIL object Math are working, which are rounded fractional numbers.