Computers Windows Internet

Javascript integer and fractional part. Remove - Integer division with remainder in JavaScript? Rounding to nearest multiple

This fixes @MarkElliot's answer to work for negative numbers as well:

Vardiv = Math.trunc(y/x); var rem = y % x;

Note that the Math methods have the advantage over the bitwise operators that they operate on numbers greater than 2 31 .

JavaScript calculates the gender of negative numbers and the remainder of non-integer numbers on the right, following the mathematical definitions for them.

FLOOR is defined as "the largest integer less than the parameter" thus:

  • positive numbers: FLOOR(X) = integer part of X;
  • negative numbers: FLOOR(X) = integer part of X minus 1 (because it should be SMALLER than the parameter, i.e. more negative!)

REMAINDER is defined as the "remainder" of a division (Euclidean arithmetic). When the dividend is not an integer, the factor is usually also not an integer, i.e. there is no remainder, but if the factor is forced to be an integer (and this is what happens when one tries to get the remainder or modulo a floating point number ), obviously, there will be a non-integer "left".

JavaScript calculates everything as expected, so the programmer has to be careful to ask the right questions (and people have to be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", instead of this: "The integer number of times the given integer GOES TO another." For positive numbers, the answer is the same for both, but not for negative numbers, because integer division (dividend by divisor) will be -1 less than the number (divisor) "goes to another" (dividend). In other words, FLOOR will return the correct answer for integer division of a negative number, but Yarin didn't ask about that!

gammax answered correctly, this code works on Yarin's instructions. On the other hand, Samuel is wrong, he didn't do the math, I think, or he would have seen it actually work (also he didn't say what was the divisor of his example, but I hope it was 3):

Remainder = X% Y = -100% 3 = -1

GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33

By the way, I tested the code on Firefox 27.0.1, it worked as expected with positive and negative numbers, as well as non-integer values, for both dividends and divisors. Example:

100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079

Yes, I noticed that there is a problem with high accuracy, but I did not have time to check it (I do not know if the problem is with Firefox, Windows 7, or with my processor's FPU). However, for Yarin's question, which only includes integers, gammax's code works just fine.

You can use the parseInt function to get a truncated result.

ParseInt(a/b)

To get the remainder, use the mod operator:

parseInt have some pitfalls with strings to avoid using base 10 radix parameter

ParseInt("09", 10)

In some cases, the string representation of a number can be scientific notation, in which case parseInt will produce an incorrect result.

ParseInt(100000000000000000000000000000000, 10) // 1e+32

This call will return 1.

Calculating the number of pages can be done in one step: Math.ceil(x/y)

If you're just sharing with the powers of two, you can use bitwise operators:

Export function divideBy2(num) ( return ; ) export function divideBy4(num) ( return ; ) export function divideBy8(num) ( return ; )

(The first is the particular, the second is the rest)

This will always truncate towards zero. Not sure if it's too late, but here it says:

Function intdiv(dividend, divisor) ( divisor = divisor - divisor % 1; if (divisor == 0) throw new Error("division by zero"); dividend = dividend - dividend % 1; var rem = dividend % divisor; return ( remainder: rem, quotient: (dividend - rem) / divisor ); )

I'm not an expert in bitwise operators, but here's another way to get an integer:

Varnum = ~~(a / b);

This will work fine for negative numbers as well, while Math.floor() will rotate in the wrong direction.

This also seems to be correct:

Varnum = (a / b) >> 0;

Math.floor(operation) returns the rounded value of the operation.

Example 1 question:

Var x = 5; vary = 10.4; varz = Math.floor(x + y); console log(z);

Prefix:

Example 2 question:

Var x = 14; vary = 5; varz = Math.floor(x%y); console log(x);

Prefix:

For some number y and some divisor x, calculate the quotient and the remainder (remainder) as:

Var quotient = Math.floor(y/x); var remainder = y % x;

Very often, calculations in JavaScript do not give exactly the results that we want. Of course, we can do anything 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're working with floating point numbers right away. This, combined with the fact that many fractional values ​​cannot be expressed with 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 shares, however, this may disappoint someone. We can also get some 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 a practical use, we can manipulate a number in some range, for example we want to round a value to the nearest whole number instead of working only with the decimal part.

Rounding decimals

To trim a decimal number, use toFixed or the toPrecision method. Both of them 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 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 the rounded value with randNum , strings will be concatenated, not numbers added:

Let randNum = 6.25; let rounded = randNum.toFixed(); // "6" console.log(randNum + rounded); > "6.256"
If you want the result to be of 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 cut off the fractional part, but also pad the decimal places, which is convenient when working with currencies:

Let wholeNum = 1 let dollarsCents = wholeNum.toFixed(2); console.log(dollarsCents); > "1.00"
Note that toPrecision will return 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 Decimals

In some cases, toFixed and toPrecision will 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 this kind of error, we can use the solution suggested 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 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 are able to round to decimal numbers. In order to simply cut off a 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 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 up or down to the nearest number, depending on what we're closest to, use Math.round():

Math.round(4.3) > 4 Math.round(4.5) > 5
Note that "half the value", 0.5 is rounded up by 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
Note that rounding down works for all numbers, including negative ones. Imagine a skyscraper with an infinite number of floors, including lower level floors (representing negative numbers). If you are in an elevator at the bottom level between 2 and 3 (which is a value of -2.5), Math.floor will take you to -3:

Math.floor(-2.5); > -3
But if you want to avoid this kind of situation, use Math.trunc , which is 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 need to always round up, use Math.ceil. Again, remembering the infinite elevator: Math.ceil will always go "up", whether the number is negative or not:

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

Round up/down as needed

If we want to round up to the nearest multiple of 5, the easiest way is to create a function that divides a number by 5, rounds it up, 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 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 an x ​​value that is within a range. For example, we might want a value from 1 to 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 it all in a function, using 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 banker's rounding, is that the rounding for this case is to the nearest even number. 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 create positional transforms for HTML elements, you might be wondering what happens if we generate decimal values ​​for our elements:

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

Sorting

Very often we need to sort some elements, for example, we have an array of game records, while 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 down immediately when it encounters 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 in 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, when looking at the code table, the character "a" has the value U+0061 (hexadecimal 0x61), while the character "C" has the code U+0043 (0x43), which comes before the character in the Unicode table. "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 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 multiple 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 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 lower case:

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 can be unpredictable:

Let 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 again be made by matching the first character of this string in the order of the characters of 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 the numbers in reverse order, swap the positions of a and b in the function.

Sorting a JSON-like structure

And 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 non-obvious thing, I hope these examples make life easier somehow.

Working with Power Functions

Exponentiation is an operation originally defined as the result of 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, the exponential function is represented as Math.pow(), in the new ES7 standard, a new exponentiation operator was 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, and the second argument is the exponent:

Math.pow(3,2) > 9
This notation means 3 squared, or 3 × 3, resulting in a result of 9. Another example could be given, of course:

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

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

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

The power function can come in handy 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 the number that gives a when cubed.

Math.cbrt(125) > 5
Math.cbrt() was introduced into 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 is not on this list, however you will find a polyfill on MDN.

Examples

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 works just as well when using negative argument values:

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

Math.sqrt(-9) > NaN
From mathematical analysis, we know that the imaginary number is understood as the square roots of negative numbers. And that might lead us to another complex number technique, 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 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, inexplicably in JavaScript, confuse the Math.pow() function with Math.exp() , which is an exponential function for numbers in general. Note: in English, "exponent" is translated as "exponent", so this is more relevant to English speakers, although there are alternative names for the exponent, such as index, power.

Mathematical constants

Working with mathematics 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 the constants are written in upper case, not CamelCase notation.

Math.abs, parseInt, parseFloat

Working with numbers in JavaScript can be a lot more complicated than you think. The obtained values ​​do not always fall within the expected ranges, sometimes the result may not be what we expected at all.

Math.abs()

The Math.abs() method returns the absolute value of a number, which reminds us of the analogous mathematical modulo a function.

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 have 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 getting some value from an unprepared array, our results can turn out to be unpredictable. We could get a string represented as "17px" as input, and this is not uncommon for us. The question is how to convert this string to 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 number system (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 denote numbers greater than 9. For example, hexadecimal numbers (base 16) use the letters A through F.

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 separate 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, as the second argument we specify 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 input.

parseFloat()

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

Syntax: parseFloat(string)

LetFP = "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 functions, it's important to keep in mind that there are some errors here, so it's necessary to check the range of expected values ​​and ultimately parse the result to ensure that the values ​​obtained are correct.
Send anonymously


In this part of our lesson, we will get acquainted with the object number as with the numeric data type container. Its proper object essence will be touched upon very superficially today.

Just like an object String contains lines of text, an object number contains numbers. Just like strings, the numbers we create automatically become object instances.

Number data type

Numbers in JavaScript are of two types: integer and floating point (there are no divisions into many types, as in other languages ​​- integer, long, short, double - are not here). Floating point numbers have an integer and a fractional part separated by a dot (regardless of locale).

These two types of numbers are not independent types and do not need a special conversion between them. If, for example, 32.5 we multiply by 0.4 , then we immediately get an integer 13 , not a fraction 13.0 , which needs to be converted to an integer value (as is often the case in other languages).

Creating a Number object

Like a string, a number is usually instantiated as an object. number, by simple assignment (unlike a string, no quotes are required).

var myNum = 21 ;

But you can also create a new object using the constructor:

var myNum = new Number ; myNum = 21 ;

In the vast majority of cases, this is unnecessary and even harmful. We will consider correct examples of such work with objects in the 4th part.

Number representation

Exponential Form

Numbers can be represented in both regular and exponential form, for example:

2e6 // no spaces!

It means: 2 x 106

If we output such a number through the document method write(), then we get the expanded number in the usual representation.

document. write(14e12);

Result:

Basic number systems

Numbers can also be represented in decimal, hexadecimal and octal systems.

whole numbers in decimal form must not start from scratch, because zero is a prefix for non-decimal systems. Just 0 is a prefix for octal values, and 0x- for hexadecimal.

For instance, 075 is the octal representation of a decimal number 61 , a 0x75- hexadecimal representation of a decimal number 117 .

Octal values ​​use digits from 0 before 7 , for hexadecimal - alphanumeric series 0123456789ABCDEF. Letters can be used in any register.

Arithmetic expressions can use any number form, but the result will always be represented as a decimal number.

Representation of numbers in other systems

Talking about an object String, we touched on the method toString(), which converts any object to a string. When converting numbers to strings, it is desirable to specify the number system as an argument.

note

The original number must be enclosed in brackets

(number). toString(system)

system- can take any value from 2 to 36.

(157 ).toString(2 ); // binary representation of 157, equals (53 ).toString(27 ); // exotic 27 representation of 53, equals

But these resulting expressions are strings. To make them real numbers in the specified number systems, you need the result of the method toString(system) convert back to number. This is no longer done by a method, but kernel function Number(object). We will talk about kernel functions in one of the next lessons, but for now, pay attention to the syntax, it looks like a function call:

var a = 1546 ; var b = a. toString(2); var c = number(b);

Or immediately, "two in one":

var a = 1546 ; var b = number(a. toString(2 ));

Note

If the original number is assigned to a variable, then it does not need to be taken in brackets when calling the method toString() .

Properties of the Number object

The general object properties constructor and prototype will be covered in the lesson about the object. Object, and now let's turn to the specific properties of the object number.

These properties are only for reading so we can't change them.

MAX_VALUE

The maximum number that can be processed in JavaScript.

Let's see what this number is:

var e = Number . MAX_VALUE document. write(e)

Result:

1.7976931348623157e+308

Plus in this case is not a sign of addition, but a positive degree, that is 1.7976931348623157 × 10 308

Note

I usually demonstrate the results with the help of actually written scripts. But too many fractional calculations can slow down page loading, and most of the results in this tutorial are handwritten, so to speak.

MIN_VALUE

And this is - respectively - the minimum value. Let's explore it.

var f = Number . MIN_VALUE document. write(f)

Result:

That is 5×10-324

A non-numeric value, which we have already met.

This property is returned by JavaScript when a numeric operation produces a non-numeric result for some reason.

NEGATIVE_INFINITY, POSITIVE_INFINITY

Once they thought something like this: "one deer, two deer, a lot of deer."

JavaScript considers it a little more "advanced": "one deer, two deer, three deer, ... , 1.7976931348623157 × 10308 deer, many deer".

This transcendent "many" is expressed by the property POSITIVE_INFINITY.

In the reverse process - dividing the unit ("one deer") into small, small pieces - the smallest read piece will be 5 × 10 -324 parts. Anything less is already NEGATIVE_INFINITY.

Methods of the Number object

Note: just like in the toString() method, in all other methods, the initial number must be enclosed in parentheses if it is provided explicitly (and not as a variable).

toExponential()

Returns a string representing a number in exponential form, with one digit before the decimal point.

Syntax:

number. toExponential(number of signs)

Argument number of signs sets the rounding precision after the decimal point. If the argument is omitted, the number of digits after the decimal point is equal to the number of digits required to represent the value.

Example:

var myFullNumber = 4659872156831598853654127 ; document. write(myFullNumber.toExponential(4))

Result:

toFixed()

Returns a string representing a fixed-point number rounded to the number of decimal places specified in the argument.

Syntax:

number. toFixed(number of signs)

Examples:

var myDecimal1 = 46.59872156831598853654127 ; var myDecimal2 = 46 ; document. write(myDecimal1.toFixed(1)) document. write("
") document. write(myDecimal2.toFixed(3))

Results:

This method is sometimes very useful. For example, the cumbersome function from the last lesson can now be represented as follows:

function anyRootPlus(x, y) ( var srcnum = Math . exp(Math. log(x) / y); varresult = (srcnum). toFixed(3); return result; )

And now we will insert it into the form and test it:

True, now integers will also have three zeros after the dot. But, knowing the behavior of numbers and strings, being able to work with conditional operators and type conversion, it is not so difficult to make the necessary numerical “design”.

toLocaleString()

Converts a numeric object to a string value, respecting the locale for decimal and thousands separators. The national currency is taken as the basis, therefore, in the Russian version, all, even integer, numbers are presented with two decimal places (kopecks):

var myDrob = 25.327 ; var myMnogo = 25635120 ; var myRoubl = 35 ; /* zoom in to see the commas better */ document. write("

" +myDrob. toLocaleString() + "

" ); document. write("

" + myMnogo. toLocaleString() + "

" ); document. write("

" + myRoubl. toLocaleString() + "

" );

Results:

toPrecision()

Returns a string representing a number with the given total number of significant digits.

Syntax:

number. toPrecision(numberNumbers)

Argument:

numberNumbers— the number of digits in the displayed line. If the specified number is greater than the number in the original number, decimal zeros are displayed.

document. write((354 ).toPrecision(8 ))

Result:

Methods toPrecision() and toLocaleString() jointly does not work, for the "Russian design" of numbers of any accuracy, you will need to write your own function. The written function can be made an additional method of the object number, we have already done something similar with the object Date(). More details in the lesson about the object Object.

toString()

Well, we have already discussed this method in detail at the beginning of the lesson.

Creating our own method

And now we will create the same method that will display a number with any number of decimal places with spaces between thousandths and with a comma as a decimal separator.

To do this, we need a rather tricky function that will deal with the conversion of strings and arrays obtained from an object instance number.

Let's declare a method:

Number.prototype.toRussianString = toRussianString

Before proceeding to the construction of the function, we formulate the tasks.

First, we need to represent the number as a string and extract the integer part, the fractional part, and the separator point from it.

Then place the necessary spaces in the integer part, round the fractional part to the number of characters that can be specified as an argument to the function (and method), and change the dot to a comma.

Let's start the function by declaring the required variables.

function toRussianString(prec) ( /* string conversion variables */ var a = "" , b = "" , c, d, e;

Looking ahead, I’ll say that the decimal part, as a result of our string perturbations, loses its “fractional” essence, and we have to work with it as with another integer. To work with it, we use the method toPrecision(), and the argument of our function (and at the same time our method) sets the value for the method toPrecision(). The minimum parameter of this method is one. And for our function, zero may also be needed (when rounded to an integer). And at the same time, the correct rounding should work even before we begin to “explode” the object. Therefore, immediately when declaring variables, we will bypass this pitfall:

/* variable that converts the given object instance to a string */ if (prec == 0 ) var str = this . toFixed(0 ).toStringtoString(10 );

Let's continue declaring variables.

/* variable for return value */ varnr1; /* variables for "dismemberment" parts */ var intpart, fractpaft, precpart, divider, dot = str. lastIndexOf("." ); /* counter */ var i;

Variable dot finds the position of the point in the string of the specified number. At this position we cut off the whole part ( intpart). If the number is integer and there is no point, its position will be less than zero. In this case, the delimiter ( divider), and the fractional part ( fractpart) must be empty strings. Otherwise, a comma is assigned to the separator, and the fractional part is cut off for further work:

if (dot< 0 ) { intpart = str; fractpart = "" ; divider = "" ;) else ( intpart = str. substring(0 , dot); fractpart = str. substring(dot + 1 , str. length); divider = "," ;}

We work with the whole part. Spaces are needed only if it has more than 3 characters:

if(intpart. length > 3 ) {

Now let's break down the following "solitaire" (all this happens inside a conditional statement):

Let's cycle through the triplets in reverse order.

First, let's collect them in a variable a without any additions, just to calculate the length of the resulting substring. After all, if the total number of digits was not divisible by 3, then a tail of 1 or 2 digits remained on the left, and now we can express it as a substring by subtracting the length of the substring with “triples” from the length of the entire string (variable c). And put a non-breaking space in front of it - (which we will then remove). What for? Since groups of three digits were read in reverse order, this initial tail must be placed at the end of the row. That is, if we had a number, say, 36748521, we need to line up 521 748 36, putting a non-breaking space in front of each group so that there is a separator for the array (after all, we need to flip them back, and this can be done using the array method reverse()).

In the last instruction of the loop, we will arrange in triplets and write the result to a variable b.

for (i=intpart. length-3; i>=0 ; i-=3 ) /* collect triplets */( a = a + intpart. substr(i, 3 ); /* find the left "tail" */ c= " " +intpart. substr(0 , intpart. length-a. length); /* place delimiters in triplets */ b=b+ " " +intpart. substr(i, 3);)

When adding strings b+c we get a string that needs to be converted into an array, and then this array is reversed and again converted into a string (this is all written into a variable d).

D = (b+c). split(" " ).reverse().toString().replace(/,/g, " " );

The array is converted to a string along with delimiter commas, we don't need them. Therefore, in the same instructions, we delete them with regular expression /, /g, where /,/ - creating a regular expression for a comma, and g- a "flag" that shows that you need to replace all expression patterns (in other words, all commas) that occur in the line. We replace them with all the same non-breaking spaces.

(Regular expressions will be discussed in more detail in the last part of the tutorial.)

And now you need to clean up something else (inside the same conditional operator if (intpart length > 3)).

The fact is that either at the beginning or at the end of our line there will be an extra non-breaking space, consisting of 6 characters: "&", "n", "b", "s", "p" and ";". Therefore, we clean up the garbage and write the result to a variable e:

if (d. substring(0 , 1 ) == "&" ) e = d. substring(6, d. length-6 ); else e = d. substring(0 , d. length-6 );

Now we can, with a clear conscience, close the entire conditional operator and write an alternative for a short number that does not need to be broken into “triples”.

) else e = intpart;

So the variable e stores the integer part of the number, and we will deal with the decimal.

Attention! When we work with the fractional part (which now needs to be treated as an integer), we must remember that when prec == 0 the function will “stumble”, so let’s immediately “plug in”:

if (prec != 0 ) (

Now you can work in peace. But there are a few more "pebbles" that we will now bypass.

First, if we have a fractional part, suppose 41 , and we set rounding to 3 digits, then the method toPrecision, taking our fractional part as an integer, will output 41.0 , that is, you need to remove the point.

Secondly, if the fractional part of the original number is greater than 3 digits, then the method toPrecision will start producing the result in exponential form. This will also have to be fought.

Therefore, we will “clean” the result through three variables: precpart, precpart1 and precpart2.

Precpart = (Number(fractpart). toPrecision(prec)). toString(10 )

Now we clean up:

/* if there is a fractional part */ if (fractpart != "") ( /* find and remove the point */ precpart1 = precpart. replace(".", "") /* check if there is an exponent, */ varplus = precpart1.lastIndexOf("e"); /* and if it exists, */ if (plus > 0 ) /* uproot, */ precpart2 = precpart1. substring(0 , plus); /* otherwise */ else /* do not change anything */ precpart2 = precpart1 ) /* if there is no fractional part, */ else /* then output zeros and get rid of the dot again */ precpart2= "," +precpart. replace("." , "" )

Since we indicated at the beginning that in the absence of a fractional part in the original number there is no comma, then in this case we need to put it again.

) else ( /* that is, if prec is still zero, just output empty lines */ precpart2= "" ; divider = "" ; }

And the final chord:

Nr1 = e + divider + precpart2; return nr1; )

Whole function:

function toRussianString(prec) ( var a = "" , b = "" , c, d, e; if (prec == 0 ) var str = this . toFixed(0 ).toString(10 ); else var str = this . toString(10 ); varnr1; var intpart, fractpaft, precpart, divider, dot = str. lastIndexOf("." ); var i; if (dot< 0 ) { intpart = str; fractpart = "" ; divider = "" ;) else ( intpart = str. substring(0 , dot); fractpart = str. substring(dot + 1 , str. length); divider = "," ;) if (intpart. length> 3 ) ( for (i=intpart. length-3; i>=0 ; i-=3 ) ( a = a + intpart. substr(i, 3 ); c= " " +intpart. substr(0 , intpart. length-a. length); b=b+ " " +intpart. substr(i, 3 );) d = (b+c). split(" " ).reverse().toString().replace(/,/g, " " ); if (d. substring(0 , 1 ) == "&" ) e = d. substring(6, d. length-6 ); else e = d. substring(0 , d. length-6 ); ) else e = intpart; if (prec != 0 ) ( precpart = (Number (fractpart). toPrecision(prec)). toString(10 ) if (fractpart != "") ( precpart1 = precpart. replace(".", "") var plus = precpart1.lastIndexOf("e"); if (plus > 0 ) precpart2 = precpart1. substring(0 , plus); else precpart2 = precpart1 ) else precpart2 = "," +precpart. replace("." , "" ) ) else ( precpart2 = "" ; divider = "" ; ) nr1 = e + divider + precpart2; return nr1; )

Now this function can be called as a method.

Var myNumber = 2569843359.6583521 document. write(myNumber. toRussianString(3 ))

Result:

You can put the method constructor and function in a library—that is, in a .js file that can be called from web page code. As you write methods for different objects, you can sort methods by library files for these objects and use additional methods.

In this article, we will take a closer look at numbers, mathematical operators, ways 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 a finite number.

This function returns false as a response if the argument is Infinity , -Infinity , NaN , or would 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 isFinite global function, JavaScript also has the Number.isFinite method. It, unlike isFinite, does not force the argument to be converted to a number.

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

isNaN function

The isNaN function is for determining if 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 multiple spaces is converted to 0 isNaN(null); //false, because null value is converted to 0 isNaN(true); //false, because true is converted to 1 isNaN(false); //false, because false value is converted to 0

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

How to explicitly convert a string to a number?

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

1. Use unary operator + The to 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

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

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

2. Function parseInt . This function is designed to convert argument to an integer. As opposed to using unary operator +, this method allows you to convert a string into a number, in which not all characters are numeric. It starts to convert the string, starting from the first character. And as soon as it encounters a character that is not a 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 indication of the base of the number system is carried out by means of 2 arguments.

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

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

3. Function parseFloat . 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 decimal notation.

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 to JavaScript with the ECMASCRIPT 2015(6) specification.

Convert number to 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 must explicitly cast the number to the 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)); ) // usage 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 it. This variant does not count an empty string, a 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 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 is not 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 translate the string into a number Number.isInteger(20); //true, because given value is a number

Even and odd numbers

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

// Function to check if a number is even function isEven(n) ( return n % 2 == 0; ) // Function to check if a number is odd function isOdd(n) ( return Math.abs(n % 2) == 1; )

But before carrying out such a check, it is desirable 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

Consider an example in which we display prime numbers from 2 to 100 using Javascript.

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

1. Using the Math.floor , Math.ceil and Math.round methods specially designed for this. The Math.floor method rounds a 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 scroll 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(precision) method. 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 accuracy of the number, then it is padded with zeros.

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

3. Through the toPrecision(precision) method. This method represents a number with the specified precision. At the same time, he can round not only the fractional, but also the whole part of the number. The resulting number can be represented by this method depending on the result in 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 NOT or OR operators.

//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, 1 should be used 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

You can determine if a number is evenly divisible using the percentage operator:

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

Number Formatting

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

For example, let's format a number according to 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 a 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%"

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))); //"1240.46"

Number Comparison

The following operators are used to compare numbers in JavaScript: == (equal to), != (not equal to), > (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 a fractional part, it is necessary to take into account the errors that may occur 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 a computer or other electronic device in the 2nd number system. Those. before performing any actions, the computer must first convert the numbers presented in the expression to the 2 number system. But, not any fractional decimal number can be represented exactly in the 2nd number system.

For example, the number 0.25 10 is converted to 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 to 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 in fact JavaScript will see this entry as follows:

0.6000000000000001==0.6

When calculating or displaying numbers with a fractional part, you must always specify the precision with which this is to 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 //toPrecision() method console.log((0.2+0.4).toPrecision(2)==(0.6).toPrecision(2)); //true

Basic math operations

JavaScript has the following math operators: + (addition), - (subtraction), * (multiply), / (division), % (modulo), ++ (increment value by 1), -- (decrease 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 operation result % 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++); //displays 3, then sets y to 4 console.log(x); //4 x = 3; console log(++x); //sets 4 and outputs x = 5; console log(x--); //outputs 5, y then sets 4 console.log(x); //4 x = 5; console log(--x); //sets to 4 and outputs In addition, there are combined operators in JavaScript: 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