Parsefloat javascript 2 decimal places. Number Rounding Methods in JavaScript

Hello. Today in the column about Javascript we will look at how to set the number of decimal places in floating point numbers in javascript. For example, you need to leave 3 decimal places when outputting, or only two.

Task: javascript number of decimal places

So, we are faced with a task: there is a calculation result in which there are numbers before the decimal point and after the decimal point. Decimal. Let's say the result is like this 1538.9891200153. But when you output, you should get a number that reflects the amount, where before the decimal point is the number of banknotes, and after - kopecks.

There are several ways to solve this problem.

Solution 1: javascript number of decimal places with toFixed method

toFixed is a javascript built-in method that is applied to any number, it takes rounding precision (that is, the number of decimal places) as a parameter.

Varnum=1538.9891200153; num_str=num.toFixed(); //num_str=1538; num_str=num.toFixed(2); //num_str=1538.98; num_str=num.toFixed(5); //num_str=1538.98912;

The precision parameter in this function must be at least 0 (does not take negative values), and at most 20.

You can also do without a variable, like this:

Num_str=(1538.9891200153).toFixed(2); //num_str=1538.98;

Solution 2: javascript number of decimal places with toPrecision method

This solution is based on the same built-in javascript method. A distinctive feature of this method is that the input parameter does not indicate the accuracy (the number of decimal places), but the total number of decimal places (both before and after the decimal point).

Varnum=1538.9891200153; num_str=num.toPrecision(5); //num_str=1538.9; num_str=num.toPrecision(7); //num_str=1538.989;

Solution without decimal places: javascript number of decimal places

If the decimal places need to be completely discarded, that is, you need to round a fractional number to an integer, then you can use the functions of the Math class: round, ceil and floor.
Round - rounds up or down (depending on the number). If the value after the decimal point is more than half, then round to big side, if less - to a smaller one. That is, if 0.51 - it will become 1, if 0.49 - 0.

Ceil - from English. the ceiling always rounds up.

Floor - from English. Gender always rounds down.

Varnum = 1538.9891200153; num_str=math.round(num); //num_str=1539; num_str=Math.floor(num); //num_str=1538; num_str=Math.ceil(num); //num_str=1539;

That's all. I hope this note helped you solve your problem. If something didn’t work out, ask questions using the green “Ask a question to a specialist” button, or in the comments.

Often calculations give results that do not fit within the desired ranges. As a result, it is necessary to JavaScript rounding up to a certain value.

Why round numbers?

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

0.1 * 0.2; > 0.020000000000000004

In practice, this will not matter, since we are talking about an error of 2 quintillion. But this can affect the result when working with numbers that represent currency values, percentages, or file sizes. Therefore, you need to do or up to a certain decimal place.

Rounding decimals

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

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

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

Note

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

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

If you want JavaScript to round to hundredths, use parseFloat() :

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

toFixed() and toPrecision() are also useful methods for truncation a large number decimal places. This is useful when working with numbers that represent monetary units:

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

Note that if the number has more digits than the precision parameter, toPrecision will return the result in scientific format:

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

How to Avoid Mistakes When Rounding Decimals

In some cases, toFixed and toPrecision do JavaScript round 5 down, and not up to more:

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

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

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

Application:

round(1.005,2); > 1.01

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

Rounding with Epsilon

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

0.1 + 0.2 === 0.3 > false

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

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

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

epsEqu(0.1 + 0.2, 0.3) > true

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

Decimal truncation

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

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

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

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

Usage:

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

Rounding to the nearest number

To carry out JavaScript round to integer, Math.round() is used:

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

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

Rounding down to the nearest whole number

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

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

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

Math.floor(-2.5); > -3

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

Math.trunc(-41.43); > -41

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

Rounding up to the nearest whole number

If you want to round up decimal numbers, use Math.ceil . You can also think of this method as an infinite elevator: Math.ceil always takes you "up", regardless of whether the number is negative or positive:

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

Rounding to nearest multiple

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

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

Usage:

roundTo5(11); > 10

If you need to perform JavaScript rounding to two decimal places, you can pass both the seed and the multiplicity to the function:

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

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

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

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

Binding to a range

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

Usage:

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

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

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.

As an answer given function returns false if the argument is Infinity , -Infinity , NaN , or will be cast to one of these special numeric values. AT 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 converts 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

Using this method note that an empty string or a string consisting of spaces and \n is converted to the number 0. In addition, it also converts the null data type and booleans to the 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 to 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 typeof operator 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 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 derive with Javascript prime numbers from 2 to 100.

// 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 computer or other electronic device produces in 2 number system. Those. before performing any actions, the computer must first convert the numbers presented in the expression to the 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 mathematical operators: + (addition), - (subtraction), * (multiply), / (division), % (remainder of division), ++ (increase 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=x-y), x*=y (x=x*y), x/= y (x=x/y), x%=y (x=x%y). x=3; y=6; x+=y; console log(x); //9 x = 3; y=6; x-=y; console log(x); //-3 x = 3; y=6; x*=y; console log(x); //18 x = 3; y=6; x/=y; console log(x); //0.5 x = 3; y=6; x%=y; console log(x); //3

Hello JavaScript lovers. You have already noticed that this language is very extraordinary and stands out in each section with its own characteristics and unusual technical solutions. Therefore, today's publication is dedicated to the topic: "JavaScript rounding".

After reading the current article, you will find out why it is necessary to round numbers, what methods and properties in js perform this function, and what distinguishes division by 0. Without changing my principles, I will attach examples to the key points of the material and describe each action in detail. Now let's start learning!

Important notes about numbers

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

Numeric variables are created in the usual way:

var numb = 35; // natural number

vardrob = 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 sometimes called "numbers in scientific format").

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

varnum = 714000.80;

alert(num.toLocaleString());

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

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

Great and mighty Math

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

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

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

Math.floor()

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

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

Math.ceil()

Again, look at the title (in this way, the material is absorbed faster). If someone does not know, then "ceil" means "ceiling". This means that numeric data will be rounded up using a non-strict inequality (>=).

alert(Math.ceil(4.5));

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

math round()

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

alert(Math.round(4.5));

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

A few more methods

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

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

toFixed()

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

varnum = 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, three more 0s were added because of the “7” parameter.

toPrecision()

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

varnum = 5656.9393;

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

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

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

The feature of division by 0 in js

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

However, JavaScript excelled here as well. So, during the execution of such an operation, no bug reports occur ... because such an operation returns "Infinity"!

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

For those who are new to the meaning of Infinity, I have explained its features below.

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

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

alert(12/0); // Infinity

alert(12.34/0); // Infinity

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

On this, perhaps, I will end. If you liked the post, be sure to subscribe to my blog. Feel free to link to interesting articles and share them with your friends. Bye Bye!

A computer