Methods for rounding numbers in JavaScript. Math object in javascript - Round, ceil and floor methods - Rounding fractional numbers Jquery rounding numbers

Often the result of calculations is a number with big amount decimal places. If this number is used for further calculations, then it can be left as is. But sometimes a number needs to be rounded, for example for display on a page. IN JavaScript rounding numbers is carried out using several methods.

The Math.round() method rounds the value to an integer.

Math.round (number)

Numbers are rounded according to mathematical rules. That is, if after the decimal point there is a number from 0 to 4, then the fractional part is simply discarded. And if after the decimal point there is a number from 5 to 9, then the fractional part is discarded, and one is added to the whole part. example:

JavaScript:

There are two more methods that round a number to a whole number. The Math.floor() method rounds down. It discards the fractional part of the number. And the Math.ceil() method rounds up. It discards the fractional part and adds one to the whole part. Example:

Of course, 5 - (-2) is 5+2. Do not forget that you will not get the number 5 in this formula. The maximum will be 4.999999999. The resulting values ​​can be rounded to the required accuracy.

If only whole numbers are needed, then the resulting values ​​can be rounded down to the nearest whole number. One must be added to the maximum so that this maximum is also possible. The formula looks like this:

integer = Math.floor(min + Math.random() * (max + 1 - min)

Let's print numbers from 10 to 15:

20
21
22
23
24

for (i=1; i<=10; i++) { rand = Math.floor(10 + Math.random() * (15 + 1 - 10)); console.log(rand); }

Comparison of fractional numbers

Mathematical calculations have one peculiarity - their results are not always absolutely accurate. This is a problem not only with JavaScript, but also with most programming languages. This happens because numbers and other data are converted into binary code, and only then calculations are made with them. In most cases, this does not lead to any particular difficulties; the calculations simply sometimes result in a number with a large number of decimal places. But there is a situation when calculation inaccuracy affects the operation of the program. This is a comparison of numbers. If different numbers are compared, then everything should be fine.

5.1 < 5.2

But if the calculation results in two identical fractional numbers, then the result of their comparison is not predictable. They can be equal, or one can be greater than the other. When a script uses such a comparison, you need to check whether the script works correctly. If there is an error in it, then you need to round off the values ​​that are being compared.

Other mathematical methods

There are quite a few methods for various mathematical calculations. They are simple and do not require additional explanation. Methods that are often used are listed in the following table:

Try doing some calculations using these methods.

In this article we will look in detail at numbers, mathematical operators, ways to convert a number into a string and vice versa, as well as many other important points.

isFinite function

The isFinite function allows you to check whether an argument is a finite number.

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

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

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

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

isNaN function

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

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

If this action needs to be performed without a type cast, then use the Number.isNaN method. This method was introduced into the language starting with ECMAScript 6.

How to explicitly convert a string to a number?

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

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

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

This method ignores spaces at the beginning and end of the line, as well as \n (line feed).

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

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

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

2. ParseInt function. This function is designed to convert argument to integer. Unlike using unary operator +, this method allows you to convert a string to a number in which not all characters are numeric. It begins to convert the string, starting from the first character. And as soon as it encounters a non-numeric character, this function stops its work and returns the resulting number.

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

This function can work with different number systems (binary, octal, decimal, hexadecimal). The base of the number system is specified using 2 arguments.

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

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

3. parseFloat function. The parseFloat function is similar to parseInt , except that it allows you to convert the argument to a fractional number.

ParseFloat("33.3%"); //33.3

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

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

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

Converting a number to a string

You can turn a number into a string using the toString method.

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

The toString method also allows you to specify the base of the number system, taking into account which you need to explicitly convert the number to a string:

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

How to check if a variable is a number

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

1. Using the isNaN and isFinite functions:

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

As a function:

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

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

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

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

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

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

Number.isInteger("20"); //false, because this method does not convert a string to a number Number.isInteger(20); //true, because this value is a number

Even and odd numbers

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

// Function for checking a number for even parity function isEven(n) ( return n % 2 == 0; ) // Function for checking a number for odd parity function isOdd(n) ( return Math.abs(n % 2) == 1; )

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

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

Prime numbers in Javascript

Let's look at an example in which we will display prime numbers from 2 to 100 using Javascript.

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

Rounding a number in Javascript

There are various ways to round a fraction to a whole number in JavaScript.

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

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

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

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

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

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

3. Using the toPrecision(accuracy) method. This method represents a number with a specified precision. At the same time, he can round not only the fractional, but also the whole part of the number. Depending on the result, this method can present the resulting number with a fixed point or in exponential form.

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

4. Using the logical operators NOT or OR.

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

Integer and fractional part of a number

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

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

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

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

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

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

Is the number divisible by an integer?

You can determine whether a number is divisible by an integer using the percentage operator:

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

Formatting numbers

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

For example, let's format a number in accordance with the regional standards that are installed in the system by default:

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

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

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

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

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

Representing a number as a percentage:

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

Break a number into digits (useGrouping property):

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

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

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

Comparison of numbers

The following operators are used to compare numbers in JavaScript: == (equal), != (not equal), > (greater than),< (меньше), >= (greater than or equal to),<= (меньше или равно).

For example, let's compare two numbers:

Console.log(2>3); //false console.log(5>=3); //true

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

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

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

Errors occur because all calculations are made by computer or other electronic device produces in 2 number system. Those. Before performing any actions, the computer must first convert the numbers presented in the expression to the 2nd number system. But not every fractional decimal number can be represented exactly in the 2nd number system.

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

0.125 × 2 = 0.25 | 0 0.25 × 2 = 0.5 | 0 0.5 × 2 = 1 | 1 0.125 10 = 0.001 2

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

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

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

0.6000000000000001==0.6

When calculating or displaying numbers with fractional parts, you must always indicate the precision with which you want to do so.

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

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

Basic Math Operations

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

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

Hello, JavaScript lovers. You have already noticed that this language is very extraordinary and in each section it 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 learn why it is necessary to round numbers, what methods and properties in js perform this function, and also what distinguishes division by 0. Without changing my principles, I will attach examples to the key points of the material and describe each action in detail. Now let's start learning!

Important notes about numbers

First, remember that in js all types of numbers (fractional and integer) belong to the type Number. In addition, they are all 64-bit, as they are stored in the “double precision” format, which is also known as the IEEE-754 standard.

Numerical variables are created in the usual way:

var numb = 35; // natural number

var drob = 0.93; //decimal representation

var numb16 = 0xFF; //Hexadecimal number system

Supports other numeric representations. So, you can also create floating point numbers (they are sometimes called “scientific numbers”).

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

var num = 714000.80;

alert(num.toLocaleString());

To work with elements of the Number type, a whole global object was provided with a bunch of various mathematical functions, whose name Math.

In addition, there are other methods that round numeric values ​​to whole numbers, tenths, hundredths, etc. Let's look at them all in more detail.

The Great and Mighty Math

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

There are analogues of Math on other platforms. For example, in popular languages ​​such as Java and C#, Math is a class that supports all the same standard functions. So as you can see, this instrument is truly great and powerful.

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

Math.floor()

I'll start with Math.floor. Pay attention to the name of the method. Logically, it becomes clear that since we are talking about rounding, and the literal translation of the word “floor” means “floor,” then this tool will round the processed values ​​down.

It is also possible that the number processed using this function remains the same. This is because rounding is carried out according to a non-strict inequality (<=). Таким образом, при отработке этой строчки кода:

alert(Math.floor(4.5));

the answer will be number 4.

Math.ceil()

Again, look at the name (this way the material is absorbed faster). If anyone doesn't know, "ceil" means "ceiling". This means that numerical data will be rounded up using a non-strict inequality (>=).

alert(Math.ceil(4.5));

As you may have guessed, the answer will be the number 5.

Math.round()

This method rounds a fraction to the nearest whole number. So, if the fractional part is in the range from 0 to 0.5 not inclusive, then rounding occurs to a smaller value. And if the fractional part is in the range from inclusive 0.5 to the next whole number, then it is rounded up to a larger whole number.

alert(Math.round(4.5));

I hope everyone thought or said the correct answer is 5.

A few more methods

JavaScript also has 2 other methods that deal with rounding numeric representations. However, they are somewhat different.

We will talk about tools such as toFixed() And toPrecision(). They are responsible not just for rounding, but for its accuracy to certain characters. Let's dig deeper.

toFixed()

Using this mechanism, you can specify how many decimal places the value should be rounded to. The method returns the result as a string. Below I have attached an option with three different options. Analyze the responses received.

var num = 5656.9393;

document.writeln(num.toFixed()); // 5657

document.writeln(num.toFixed(2)); // 5656.94

document.writeln(num.toFixed(7)); // 5656.9393000

As you can see, if you do not specify an argument, then toFixed ()) will round the fractional value to the whole numbers. The third line is rounded up to 2 characters, and in the fourth, due to the parameter “7”, three more 0s were added.

toPrecision()

This method works a little differently. In place of the argument, you can either leave an empty space or set a parameter. However, the latter will round numbers to the specified number of digits, regardless of the comma. Here are the results produced by the program, rewritten from the previous example:

var num = 5656.9393;

document.writeln(num.toPrecision()); // 5656.9393

document.writeln(num.toPrecision(2)); // 5.7e+3

document.writeln(num.toPrecision(7)); // 5656.939

Feature of division by 0 in js

As you know from math lessons, you cannot divide by zero. This rule was taken as a basis by most creators of programming languages. Therefore, when dividing by zero, all programs generate an error.

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

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

For those who are encountering the Infinity value for the first time, I have explained its features below.

Infinity – means infinity and fully corresponds to the mathematical sign ∞.

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

alert(12/ 0); //Infinity

alert(12.34/ 0); //Infinity

alert (-3/ 0); // -Infinity

I guess I'll end here. If you liked the publication, be sure to subscribe to my blog. Don’t be greedy with links to interesting articles and share them with your friends. Bye bye!

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

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

Syntax

Math.round(x)

Parameters

x A number.

Return value

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

Description

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

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

Examples

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

Demonstrative Implementation

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

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

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

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

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

Specifications

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

Browser compatibility

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

Update compatibility data on GitHub

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

Often calculations produce results that are outside the desired ranges. As a result, it is necessary to implement JavaScript rounding up to a certain value.

Why round numbers?

JavaScript does not store integers because their values ​​are represented as floating point numbers. Many fractions cannot be represented as a number with a specific finite number of decimal places, so JavaScript can generate results like the following:

0.1 * 0.2; > 0.020000000000000004

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

Rounding decimal numbers

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

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

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

Note

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

console.log(randNum + rounded); > "6.256"

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

var randNum = 6.25; var rounded = parseFloat(randNum.toFixed(1)); console.log(rounded); > 6.3

toFixed() and toPrecision() are also useful methods for trimming large quantity decimal places. This is useful when working with numbers representing monetary units:

var wholeNum = 1 var dollarsCents = wholeNum.toFixed(2); console.log(dollarsCents); > "1.00"

Note that if a number has more digits than the precision specified, toPrecision will output the result in scientific format:

var num = 123.435 num.toPrecision(2); > "1.2e+2"

How to avoid mistakes when rounding decimals

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

var numTest = 1.005; numTest.toFixed(2); > 1;

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

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

Application:

round(1.005,2); > 1.01

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

Rounding with epsilon

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

0.1 + 0.2 === 0.3 > false

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

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

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

epsEqu(0.1 + 0.2, 0.3) > true

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

Truncation of decimal numbers

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

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

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

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

Usage:

var randInt = 35.874993; truncated(randInt,3); > 35.874

Round to the nearest number

To implement JavaScript rounding to the nearest integer, Math.round() is used:

Math.round(4.3) > 4 Math.round(4.5) > 5

Note that " half values", such as .5, are rounded up.

Round down to the nearest whole number

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

Math.floor(42.23); > 42 Math.floor(36.93); > 36

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

Math.floor(-2.5); > -3

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

Math.trunc(-41.43); > -41

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

Round up to the nearest whole number

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

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

Round to the nearest multiple

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

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

Usage:

roundTo5(11); > 10

If you need JavaScript to round to two decimal places, you can pass both the seed and the multiple to the function:

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

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

var initialNumber = 11; var multiple = 10; roundToMultiple(initialNumber, multiple); > 10;

To round values ​​up or down only, replace round with ceil or floor in the function.

Range binding

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

Usage:

var lowBound = 1; var highBound = 100; var numInput = 123; var clamped = Math.max(lowBound, Math.min(numInput, highBound)); console.log(clamped); > 100;

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

Internet