Contacts

Methods rounding numbers in JavaScript. Simple rounding rules in JavaScript. We study the methods and apply in practice ParseFloat JavaScript 2 decimal sign



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 zero. 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 the best way I saw is multiplied by 10 per number of numbers, then make math.round, and then finally divide 10 by 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)

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

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 of this method is that the parameter taken to the input indicates not accuracy (the number of semicolons), but the total number of characters (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.

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.



Did you like the article? Share it