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

💖 Do you like it? Share the link with your friends
Very often, calculations in JavaScript do not give exactly the results we want. Of course, we can do whatever we want with numbers - round up or down, set ranges, cut off unnecessary numbers to a certain number of decimal places, it all depends on what you want to do with this number in the future. Why is rounding necessary? One of the interesting aspects of JavaScript is that it doesn't actually store integers, we work straight away with floating point numbers. This, combined with the fact that many fractional values ​​cannot be expressed in a finite number of decimal places, in JavaScript we can get results like this:

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

Rounding numbers has practical use, we may be manipulating a number within some range, for example we want to round the value to the nearest whole number rather than working only with the decimal part.

Rounding decimal numbers To cut off decimal number, use toFixed or the toPrecision method. Both of them take a single argument, which determines, respectively, how many significant figures(i.e. the total number of digits used in the number) or decimal places (the number after the decimal point) must include the result:
  • If an argument is not defined for toFixed(), it will default to zero, which means 0 decimal places, the argument has a maximum value of 20.
  • If no argument is given to toPrecision, the number is left untouched
  • let randNum = 6.25; randNum.toFixed(); > "6" Math.PI.toPrecision(1); > "3" randNum = 87.335; randNum.toFixed(2); > "87.33" randNum = 87.337; randNum.toPrecision(3); > "87.3"
    Both the toFixed() and toPrecision() methods return a string representation of the result, not a number. This means that when summing a rounded value with randNum, it will produce a concatenation of strings rather than a sum of numbers:

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

    Let randNum = 6.25; let rounded = parseFloat(randNum.toFixed(1)); console.log(rounded); > 6.3
    Please note that values ​​of 5 are rounded except in rare cases.

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

    Let wholeNum = 1 let dollarsCents = wholeNum.toFixed(2); console.log(dollarsCents); > "1.00"
    Note that toPrecision will produce the result in scientific notation if the number of integers is greater than the precision itself:

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

    How to Avoid Rounding Errors with Decimals In some cases, toFixed and toPrecision round the value 5 down and up:

    Let numTest = 1.005; numTest.toFixed(2); > "1.00"
    The result of the calculation above should have been 1.01, not 1. If you want to avoid a similar error, we can use the solution proposed by Jack L Moore, which uses exponential numbers for the calculation:

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

    Round(1.005,2); > 1.01
    If you want a more robust solution than the one shown above, you can go to MDN.

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

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

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

    Cutting off the fractional part All the methods presented above can round to decimal numbers. In order to simply cut a number to two decimal places, you must first multiply it by 100, and then divide the resulting result by 100:

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

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

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

    Rounding to the Nearest Number To round a decimal number to the nearest number up or down, whichever we're closest to, use Math.round():

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

    Rounding down to the nearest whole number If you want to always round down, use Math.floor:

    Math.floor(42.23); > 42 Math.floor(36.93); > 36
    Please note that rounding down works for all numbers, including negative numbers. Imagine a skyscraper with an infinite number of floors, including floors on the bottom level (representing negative numbers). If you are in an elevator on the lowest level between 2 and 3 (which represents a value of -2.5), Math.floor will take you to -3:

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

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

    Rounding up to the nearest whole number On the other hand, if you always need to round up, use Math.ceil. Again, remember the infinite elevator: Math.ceil will always go "up", regardless of whether the number is negative or not:

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

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

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

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

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

    Let initialNumber = 11; let multiple = 10; roundToMultiple(initialNumber, multiple); > 10;

    Fixing a Number in a Range There are many cases where we want to get a value of x that lies within a range. For example, we might need a value between 1 and 100, but we ended up with a value of 123. To fix this, we can use min (returns the smallest of a set of numbers) and max (returns the largest of any set of numbers). In our example, the range is from 1 to 100:

    Let lowBound = 1; let highBound = 100; let numInput = 123; let clamped = Math.max(lowBound, Math.min(numInput, highBound)); console.log(clamped); > 100;
    Again, we can reuse the operation and wrap the whole thing in a function, using the solution proposed by Daniel X. Moore:

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

    NumInput.clamp(lowBound, highBound); > 100;

    Gaussian rounding Gaussian rounding, also known as banker's rounding, involves rounding to the nearest even number. This rounding method works without statistical error. The best decision was suggested by Tim Down:

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

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

    Since JavaScript is often used to create positional mappings for HTML elements, you might be wondering what would happen if we generated decimal values ​​for our elements:

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

    Sorting Very often we need to sort some elements, for example, we have an array of game records, and they must be organized in descending order of player rank. Unfortunately, the standard sort() method has some surprising limitations: it works well with frequently used in English words, but immediately breaks when encountering numbers, unique characters or words in uppercase. Sorting Alphabetically It would seem that sorting an array alphabetically should be a simple task:

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

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

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

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

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

    Function caseSort(arr) ( arr.sort(function (a, b) ( return a.toLowerCase().localeCompare(b.toLowerCase()); )); ) let fruit = ["butternut squash", "apricot", "Cantaloupe"]; caseSort(fruit) > ["apricot", "butternut squash", "Cantaloupe"]

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

    Let highScores = ; highScores.sort(); >
    The thing is that the sort() method performs a lexicographic comparison: which means that the numbers will be converted into a string and the comparisons will again be made by matching the first character of that string in the order of the characters in the Unicode table. Therefore, we again need to define our sort order:

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

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

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

    Scores.sort((a, b) => b.score - a.score));
    For older browsers that do not have this support:

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

    Working with Power Functions Exponentiation is an operation originally defined as the result of repeatedly multiplying a natural number by itself; the square root of a is the number that gives a when squared. We could use these functions constantly in everyday life in mathematics lessons, including when calculating areas, volumes, or even in physical modeling.

    In JavaScript power function introduced as Math.pow(), the new ES7 standard introduced a new exponentiation operator, " * * ".

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

    Math.pow(3,2) > 9
    This form of notation means 3 squared, or 3 × 3, which leads to the result 9. Another example can be given, of course:

    Math.pow(5,3); > 125
    That is, 5 cubed, or 5 × 5 × 5, is equal to 125.

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

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

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

    Square and cube root Math.sqrt() and Math.cbrt() are the opposite of Math.pow(). As we remember, the square root of a is the number that gives a when squared.

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

    Math.cbrt(125) > 5
    Math.cbrt() was only recently introduced into the JavaScript specification, and is therefore only supported in modern browsers: Chrome 38+, Firefox and Opera 25+, and Safari 7.1+. You will notice that Internet Explorer isn't on this list, but you'll find a polyfill on MDN.

    Examples Of course, we can use non-integer values ​​in one of these functions:

    Math.pow(1.25, 2); > 1.5625 Math.cbrt(56.57) > 3.8387991760286138
    Please note that this works quite well when using negative values arguments:

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

    Math.sqrt(-9) > NaN
    From mathematical analysis we know that an imaginary number refers to the square roots of negative numbers. And this may lead us to another technique for working with complex numbers, but that's another story.

    You can use fractions in Math.pow() to find the square and cube roots of numbers. Square root uses an exponent of 0.5:

    Math.pow(5, 0.5); // = Math.sqrt(5) = 5 ** (1/2) > 2.23606797749979
    However, due to the vagaries of floating point, you can't exactly guess the correct result:

    Math.pow(2.23606797749979,2) > 5.000000000000001
    In such situations, you will have to resort to cutting off signs from the number or rounding to some value.

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

    Mathematical Constants Working with math in JavaScript is made easier by a number of built-in constants. These constants are properties of the Math object. It is worth noting that constants are written in uppercase, not CamelCase notation. Math.abs, parseInt, parseFloat Working with numbers in JavaScript can be a lot more complicated than it seems. The obtained values ​​do not always fall within the expected ranges; sometimes the result may not be at all what we expected. Math.abs() The Math.abs() method returns the absolute value of a number, which reminds us of a similar mathematical function for the modulus of a number.

    Let newVal = -57.64; Math.abs(newVal); > 57.64
    Math.abs(0) always returns zero, but if we put a minus sign in front of the -Math.abs(NUM) function we will always get a negative value.

    Math.abs(0); > -0

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

    Syntax: parseInt(string, radix);

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

    Let's look at an example of working with CSS properties, where, relatively speaking, we can get the following value:

    Let elem = document.body; let centerPoint = window.getComputedStyle(elem).transformOrigin; > "454px 2087.19px"
    We can split the values ​​by spaces:

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

    Let centerX = parseInt(centers, 10); > 454 let centerY = parseInt(centers, 10); >2087
    As you can see, with the second argument we indicate the number system into which the number will be converted; this parameter is optional, but it is recommended to use it if you do not know which string will be received as input.

    parseFloat() From the example above, you probably noticed that parseInt discards the fractional part. In our case, parseFloat can work with floating point numbers. Again, this can be useful when parsing CSS and other tasks, especially when working with floating point percentages.

    Syntax: parseFloat(string)

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

    We understand that parseInt() and parseFloat() are extremely useful features, it is important to note that there are still some errors involved, so it is necessary to check the range of expected values ​​and ultimately analyze the result to ensure that the values ​​obtained are correct.
    Send anonymously

    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

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsround
    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

    Now let's look at the floor method (translated as gender), which works opposite to the ceil method, i.e. it rounds a fraction down.

    var age = 35.97 ;

    age = Math.floor(age); /* Round the value of the age variable down */

    document.write(age);

    As you can see, the floor method rounded the number 35.97 to 35, that is, down. Despite the fact that 0.97 is greater than 0.5 (cm. ).

    This lesson looked at the Math object's methods for rounding fractional decimal numbers.

    Now you need to do your homework.

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

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

    Source array:

    var numberArray = ;

    At first, solving this task may seem almost identical to solving homework problems from first three lessons this topic. But not everything is so simple...

    Solution #1 - Attention

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

    function decimal (anyArray ,method ) /* Create a function with two parameters */
    {

    for (i = 0 ; i< anyArray .length ; i ++ )

    {
    document.write(anyArray
    " )

    anyArray = Math.method(anyArray); /* Using one of the methods of the Math object, we round the current element of the array */

    document.write(anyArray + "

    " )
    }

    decimal (numberArray, round ) /* Call the function and specify two parameters for it. But you CANNOT specify the method NAME as a function parameter */

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

    But we won’t get any result, since you CANNOT specify the method NAME as a function parameter.

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

    decimal (numberArray, "round") - but such a notation will also not be correct!!!

    Solution No. 2 - Correcting the previous solution

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

    var numberArray = ;

    function decimal (anyArray ) /* Create a function with one parameter */
    {

    for (i = 0 ; i< anyArray .length ; i ++ ) /* Перебираем элементы массива */

    {
    document.write(anyArray + " - source array element
    " ) /* Output the current element of the array */

    /* Using the round method of the Math object, we round the current element of the array */

    document.write(anyArray + " - Rounded element

    " ) /* Output the ROUNDED array element */
    }

    decimal (numberArray ) /* Call the function and specify one parameter - the original array */


    35 - Rounded element


    13 - Rounded element


    17 - Rounded element


    79 - Rounded element

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

    Solution #3 - Function with two parameters

    Here the problem is solved correctly. To do this I had to remember javascript conditions theme and apply several conditions simultaneously.

    var numberArray = ;

    function decimal(anyArray,method)
    {
    for (i = 0 ; i< anyArray .length ; i ++ )
    {
    document.write(anyArray + " - source array element
    " );

    if (method
    {
    anyArray = Math.round(anyArray);
    document.write(anyArray + " - standard rounding

    " )
    }

    Else if(method
    {

    document.write (anyArray + " - round up

    " )
    }

    else if(method
    {

    document.write (anyArray + " - round down

    " )
    }

    }
    }
    decimal (numberArray, "ceil") /* The second parameter of the function - in quotes, indicate the name of one of the methods */

    34.82 - initial element of the array
    35 - round up

    12.9 - initial array element
    13 - round up

    17.01 - initial element of the array
    18 - round up

    78.51 - initial element of the array
    79 - round up

    That's the right decision Homework. Here two parameters are specified for the function according to the condition.

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

    Solution #4 - Function with two parameters + prompt method

    I decided to optimize the previous solution a little and added prompt method which causes modal window, containing a field for entering information.

    Now, thanks to this, you can enter the name of one of the methods round , floor or ceil in the input field and get the corresponding result.

    var numberArray = ;

    function decimal(anyArray,method)
    {
    for (i = 0 ; i< anyArray .length ; i ++ )
    {
    document.write(anyArray + " - source array element
    " );

    if (method == "round" ) /* 1st condition */
    {
    anyArray = Math.round(anyArray);
    document.write(anyArray + "

    " )
    }

    Else if(method == "ceil" ) /* 2nd condition */
    {
    anyArray = Math.ceil(anyArray);
    document.write(anyArray + "

    " )
    }

    else if(method == "floor" ) /* 3rd condition */
    {
    anyArray = Math.floor(anyArray);
    document.write(anyArray + "

    " )
    }

    /* Add the prompt method */

    var method = prompt ("Enter one of the methods: round, ceil or floor" );

    if (method == "floor" ) /* 1st condition */
    {
    document.write("You have entered a method " + method + " that rounds numbers DOWN

    " )
    }

    else if (method == "round" ) /* 2nd condition */
    {
    document.write("You have entered a method " + method + " that rounds numbers according to standard rules

    " )
    }

    else if (method == "ceil" ) /* 3rd condition */
    {
    document.write("You have entered a method " + method + " that rounds numbers up

    " )
    }

    else /* Otherwise... */
    {
    document.write("You have not entered or entered a method incorrectly

    " )
    }

    decimal (numberArray, method ) /* Call the function */

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

    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 an answer 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

    Except global function isFinite JavaScript also has a method called Number.isFinite . 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 the 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 Note 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 an argument to an integer. Unlike using the 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 derive from using Javascript prime numbers from 2 to 100.

    // 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 (больше), < (меньше), >= (greater than or equal to), 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 in binary system converted 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



    tell friends