23.07.2020

Rounding numbers in JavaScript. Simple javascript rounding rules. Learning Methods and Practicing Rounding Up to the Nearest Integer


Often times, computations 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 curious aspects of JavaScript is that it doesn't actually store integers, we are immediately working with floating point numbers. This, coupled with the fact that many fractional values ​​cannot be expressed in finite numbers 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 at all, in our case we are talking about an error in quintillion parts, however, this may disappoint someone. We can get a slightly strange result when working with numbers that represent values ​​of currencies, percentages, or file sizes. In order to correct these inaccuracies, we just need to be able to round the results, while it is enough to set the decimal precision.

Rounding numbers has practical use, we can manipulate a number in a certain range, for example, we want to round the value to the nearest integer, and not work only with the decimal part.

Rounding decimal numbers

To strip off the decimal number, use toFixed or the toPrecision method. They both take a single argument, which determines, respectively, how many significant digits (i.e. the total number of digits used in the number) or decimal places (the number after the decimal point) the result should include:
  1. If the argument is not defined for toFixed (), then it will default to zero, which means 0 decimal places, the argument has a maximum value of 20.
  2. If no argument is given for 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 toFixed () and toPrecision () return a string representation of the result, not a number. This means that when the rounded value is summed with randNum, the strings will be concatenated, not the sum of the numbers:

Let randNum = 6.25; let rounded = randNum.toFixed (); // "6" console.log (randNum + rounded); > "6.256"
If you want the result to have 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
Note that 5 values ​​are rounded except in rare cases.

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

Let wholeNum = 1 let dollarsCents = wholeNum.toFixed (2); console.log (dollarsCents); > "1.00"
Please note that toPrecision will give the result in exponential 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 decimal numbers

In some cases, toFixed and toPrecision rounds 5 down and up:

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

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 head over 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 can produce results similar to the following:

0.1 + 0.2 === 0.3> false
We use Math.EPSILON in our function to get the correct comparison:

Function epsEqu (x, y) (return Math.abs (x - y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }
The function takes two arguments: the first 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.

Fractional clipping

All methods presented above know how to round to decimal numbers. In order to simply cut off the number to two decimal places, you must first multiply it by 100, and then divide the result by 100:

Function truncated (num) (return Math.trunc (num * 100) / 100;) truncated (3.1416)> 3.14
If you want to accommodate any number of decimal places, you can use double bitwise 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 up or down, whichever comes closest, use Math.round ():

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

Round down to nearest whole number

If you want to always round down, use Math.floor:

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

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

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

Round up to nearest whole number

On the other hand, if you always need to round up, use Math.ceil. Again, remembering the endless lift: 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 as required

If we want to round to the nearest multiple of 5, the simplest way is to create a function that divides a 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 an initial value and a 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 x within a range. For example, we might want a value between 1 and 100, but we get 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, let's use the solution suggested 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 bank rounding, is where it rounds to the nearest even. This rounding method works without statistical error. The best solution 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 point in CSS:

Since JavaScript is often used to generate positional transformations on HTML elements, you might wonder what happens if we generate decimal values ​​for our elements:

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

Sorting

Very often we have to sort some elements, for example, we have an array of game records, and they must be organized in descending order of the rank of the players. Unfortunately, the standard sort () method has some surprising limitations: it works well with commonly used English words, but breaks immediately when faced with numbers, unique characters, or uppercase words.

Sort alphabetically

It would seem that sorting an array alphabetically should be the simplest 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 a unique code for any character, 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 system 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, which can contain mixed case of first letters, we need to either convert all elements temporarily to lower case, or define our own 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 to get an array sorted in reverse alphabetical order, just swap positions 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"]
It is worth noting here that localeCompare is used with arguments, you 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"]

Numeric sort

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

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

Let highScores =; highScores.sort (function (a, b) (return a - b;)); >
Again, to sort the 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 don't have this support:

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

Working with power functions

Exponentiation is an operation originally defined as the result of multiple multiplication of a natural number by itself, the square root of a is the number that gives a when squared. We could use these functions all the time in everyday life in mathematics lessons, including when calculating areas, volumes, or even in physical modeling.

In JavaScript, the exponential function is represented as Math.pow (), in the new ES7 standard, a new exponentiation operator is introduced - "* *".

Exponentiation

To raise a number to the nth power, use the Math.pow () function, where the first argument is the number to 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. You can give another example, of course:

Math.pow (5.3); > 125
That is, 5 cubed, or 5 x 5 x 5, equals 125.

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

3 ** 2 > 9
Currently, support for this operator is rather limited, so it is not recommended to use it.

A power function can come in handy in a wide 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 the Math.pow () function. Remember that 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 the number a is the number that gives a when raised to a cube.

Math.cbrt (125)> 5
Math.cbrt () was introduced to the JavaScript specification very recently and is therefore only supported in modern browsers: Chrome 38+, Firefox and Opera 25+, and Safari 7.1+. You will notice that Internet Explorer not on this list, but polyfill can be found on MDN.

Examples of

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

Math.pow (1.25, 2); > 1.5625 Math.cbrt (56.57)> 3.8387991760286138
Note that this also works fine for negative argument values:

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

Math.sqrt (-9)> NaN
We know from mathematical analysis that an imaginary number is understood as the square roots of negative numbers. And that might lead us to another technique for working with complex numbers, but that's another story.

You can use fractional values ​​in Math.pow () to find the square and cube roots of numbers. The 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 cannot accurately guess the correct result:

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

Some, for some unknown reason in JavaScript, confuse the Math.pow () function with Math.exp (), which is an exponential function for numbers in general. Note: in English language"Exponent" translates to "exponent", so it is more likely to refer to English speakers, although there are alternative names for the 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 sounds. 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 absolute value numbers, which reminds us of the analogous mathematical function of the absolute value of the number a.

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

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 getting some value from an unprepared array, our results can be unpredictable. We could have received a string represented as "17px" as input, and this is not uncommon for us. The question is how to convert this string to 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 a conversion from decimal, 8 to octal, 16 to hex, and so on. If the base is greater than 10, then letters are used to denote numbers greater than 9. For example, hexadecimal numbers (base 16) use the letters A through F.

Let's consider 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 values ​​by spaces:

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

Let centerX = parseInt (centers, 10); > 454 let centerY = parseInt (centers, 10); > 2087
As you can see, as the second argument, we indicate the number system to 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 sent to the input.

parseFloat ()

From the example above, you may have noticed that parseInt discards the fractional part. In our case, parseFloat is able to work with floating point numbers. Again, this can be useful when parsing CSS and other tasks, especially when dealing 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 keep in mind that errors cannot be avoided here, so it is necessary to check the range of expected values ​​and ultimately analyze the result to ensure that the obtained values ​​are correct.
Send anonymously



JavaScript math, rounding to 2 decimal places (9)

I have the following JavaScript syntax:

Var discount = Math.round (100 - (price / listprice) * 100);

This is rounded to the nearest whole number. How can I return the result with two decimal places?

Here is a working example

Var value = 200.2365455; result = Math.round (value * 100) / 100 // result will be 200.24

To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here is some sample code for the game.

Var testNum = 134.9567654; var decPl = 2; var testRes = roundDec (testNum, decPl); alert (testNum + "rounded to" + decPl + "decimal places is" + testRes); function roundDec (nbr, dec_places) (var mult = Math.pow (10, dec_places); return Math.round (nbr * mult) / mult;)

The best and simplest solution I have found is

Function round (value, decimals) (return Number (Math.round (value + "e" + decimals) + "e -" + decimals);) round (1.005, 2); // 1.01

Slight variation on the accepted answer. toFixed (2) returns a string and you always get two decimal places. These can be zeros. If you want to suppress trailing zero (s) just do this:

Var discount = + ((price / listprice) .toFixed (2));

Edited: I just discovered what seems to be a bug in Firefox 35.0.1, which means the above might give NaN some values.
I changed my code to

Var discount = Math.round (price / listprice * 100) / 100;

This gives the number to two decimal places. If you need three, you will be multiplying and dividing by 1000, and so on.
The OP wants two decimal places always, but if toFixed () is broken in Firefox, it needs to be fixed first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

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

Var discount = Math.round ((100 - (price / listprice) * 100) * 100) / 100;

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

I think that The best way which I saw is multiply by 10 by the number of digits, then do Math.round, and then finally divide by 10 by the number of digits. Here's a simple function that I use in typescript:

Function roundToXDigits (value: number, digits: number) (value = value * Math.pow (10, digits); value = Math.round (value); value = value / Math.pow (10, digits); return value; )

Or simple javascript:

Function roundToXDigits (value, digits) (if (! Digits) (digits = 2;) value = value * Math.pow (10, digits); value = Math.round (value); value = value / Math.pow (10 , digits); return value;)

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

Var discount = (price / listprice) .toFixed (2);

toFixed rounds up or down for you based on values ​​greater than 2 decimal places.

Change. As mentioned by others, this will convert the result to a string. To avoid this:

Var discount = + ((price / listprice) .toFixed (2));

Editing 2- As mentioned in the comments, this function is not executed with some precision, for example in the case of 1.005 it will return 1.00 instead of 1.01. If accuracy is so important, I found this answer: https: //.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.

One minor modification is required, but the function in the answer above returns integers when it rounds to one, so for example 99.004 will return 99 instead of 99.00, which is not ideal for displaying prices.

Edit 3- It seems that toFixed on the actual return STILL was twisting some numbers, this final edit seems to work. Geez so many reparations!

Var discount = roundTo ((price / listprice), 2); function roundTo (n, digits) (if (digits === undefined) (digits = 0;) var multiplicator = Math.pow (10, digits); n = parseFloat ((n * multiplicator) .toFixed (11)); var test = (Math.round (n) / multiplicator); return + (test.toFixed (digits));)

Edit 4“You guys are killing me. Edit 3 fails on negative numbers without digging into why it is easier to just make the negative number positive before doing rounding and then putting it back before returning the result.

Function roundTo (n, digits) (var negative = false; if (digits === undefined) (digits = 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 DECALILS

x = .123456 result = Math.round (x * 100) / 100 // result .12

THREE DECIMALITIES

x = .123456 result = Math.round (x * 1000) / 1000 // result .123

Function round (num, dec) (num = Math.round (num + "e" + dec) return Number (num + "e -" + dec)) // Round to a decimal of your choosing: round (1.3453,2)

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

After reading the current article, you will learn why it is necessary to round numbers, which methods and properties in js perform this function, and also how division by 0 stands out. 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 kinds of numbers (fractions and integers) are of the type Number... In addition, they are all 64-bit, since they are stored in the "double precision" format, which is also known as the IEEE-754 standard.

Numeric 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 as well. So, you can still create floating point numbers (they are also sometimes called "numbers in scientific format").

The support appeared very interesting method toLocaleString (), which formats all numeric parameters according to the specifications written in ECMA 402. This makes large numbers, phone numbers, currencies and even percentages beautifully displayed in the dialog box.

var num = 714000.80;

alert (num.toLocaleString ());

To work with elements of type Number, a whole global object was provided with a bunch of all kinds of mathematical functions, the name of which is Math.

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

Great and mighty Math

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

On other platforms, there are analogies for Math. For example, in popular languages ​​like Java and C #, Math is a class that supports all of the same standard functionality. So as you can see, this instrument is really great and powerful.

Now I want to walk on specific methods, responsible for rounding, and tell 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 ​​downward.

It is also possible that the processed number 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 the number 4.

Math.ceil ()

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

alert (Math.ceil (4.5));

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

Math.round ()

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

alert (Math.round (4.5));

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

A few more methods

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

It will be about tools such as toFixed () and toPrecision ()... They are responsible not only for rounding, but for its accuracy to certain signs. Let's dig deeper.

toFixed ()

Using this mechanism, you can specify to how many decimal places the value should be rounded. The method returns the result as a string. Below I have attached a variant with three different variants. Analyze the answers you 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 - because of the "7" parameter, three more 0s were added.

toPrecision ()

This method works in a slightly different way. In place of the argument, you can leave either an empty space or set a parameter. However, the latter will round numbers to the specified number of digits, ignoring the comma. Here are the results of 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

The division by 0 feature in js

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

However, JavaScript has distinguished itself here too. So, during the execution of such an operation, no error messages appear ... because such an operation returns "Infinity"!

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

For those who first encounter the Infinity value, below I explained its features.

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

It could 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

On this, perhaps, and finish. If you liked the publication, then be sure to subscribe to my blog. Don't be greedy with links to interesting articles and share them with your friends. Bye Bye!

This article will take a closer look at numbers, mathematical operators, how to convert a number to a string and vice versa, as well as many other important points.

IsFinite function

The isFinite function allows you to check if an argument is finite.

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 Number.isFinite method. Unlike isFinite, it does not force the argument to a number.

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

IsNaN function

The isNaN function is designed to determine if an argument is a number or can be converted to it. 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 space or several spaces are converted to 0 isNaN (null); // false, because null is converted to 0 isNaN (true); // false, because true converts to 1 isNaN (false); // false, because false converts to 0

If you need to perform this action without typecasting, then use the Number.isNaN method. This method has been introduced into the language since ECMAScript 6.

How can I explicitly convert a string to a number?

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

1. Use unary + operator to be placed before the value.

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

This method ignores leading and trailing whitespace and \ n (line feed).

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

Using this way it is necessary to pay attention to the fact that empty line or a string consisting of spaces and \ n is converted to 0. In addition, it also converts the data type to null and boolean values to the number.

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

2. The parseInt function. This function is designed to convert argument to an integer... As opposed to using unary operator +, this method allows you to convert a string to a number, in which not all characters are numeric... It starts converting the string, starting at 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 radix 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 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. The parseFloat function. ParseFloat is similar to parseInt, except that it converts the argument to a fraction.

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

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

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

Convert number to string

You can convert a number to 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 it is necessary to explicitly cast the number to a string:

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

How to check if a variable is a number

You can determine if 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 specified value number or can be reduced to it. This option does not treat an empty string, a string of spaces, null, Infinity, -Infinity, true or false as a number.

2.Using operator typeof and functions isFinite, isNaN:

// function that checks if the value is a number function isNumber (value) (return typeof value === "(! LANG: 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 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 if the specified value is an integer.

Number.isInteger ("20"); // false, because this method does not translate the string to the number Number.isInteger (20); // true, because the given 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 the number for evenness function isEven (n) (return n% 2 == 0;) // Function for checking the number for oddness 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");))

Javascript primes

Let's consider an example in which we display primes from 2 to 100 using Javascript.

// A function that checks if the 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 fractional number to an integer value in JavaScript.

1. Using the specially designed methods Math.floor, Math.ceil and Math.round. The Math.floor method rounds the fractional number down to the nearest integer, i.e. simply discards the fractional part. Math.ceil rounds a fractional number up to the nearest integer. 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 curl is down.

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 (precision). This method rounds the fractional part of a number to the 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. Through the toPrecision method. This method represents a number with the specified precision. Moreover, he can round off not only the fractional, but also the whole part of the number. This method can represent the resulting number, depending on the result, 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 logical operators NOT or OR.

// via double logical negation console.log (~~ 7.9); // 7 // by using a 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 () method and parseInt ():

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 by dividing the first number by the second. In this case, 1 must be used as the 2 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 even divisible

You can determine whether a number is evenly divisible using the percent operator:

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

Formatting numbers

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

For example, let's format the number according to the regional standards that are installed on 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"

Representation of a number as a percentage:

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

Split the 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"

Comparing numbers

JavaScript uses the following operators to compare numbers: == (equal),! = (Not equal),> (greater than),< (меньше), >= (greater than or equal),<= (меньше или равно).

For example, let's compare two numbers:

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

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

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

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

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

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

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 to a 2 system only with a certain precision:

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 the two numbers and the comparison results. Those. it turns out that in fact JavaScript will see this record as follows:

0.6000000000000001==0.6

When calculating or displaying numbers with a fractional part, you must always indicate the precision with which it must be done.

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 by 1), - (decrease 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 ++); // prints 3, y sets 4 later console.log (x); // 4 x = 3; console.log (++ x); // sets 4 and prints x = 5; console.log (x--); // prints 5, y sets 4 later console.log (x); // 4 x = 5; console.log (- x); // sets 4 and outputs In addition, JavaScript has combined operators: x + = y (x = x + y), x- = y (x = xy), 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


2021
maccase.ru - Android. Brands. Iron. news