Parseint в javascript что такое
Перейти к содержимому

Parseint в javascript что такое

  • автор:

parseInt and other options for parsing numbers in javaScript

The parseInt function is one of several ways to convert a string to a number in javaScript. The parseInt method does convert a string or number to an integer, but technically it is still a float as all numbers in javaScript are double precision floating point numbers.

So when using the javaScript parseInt method to produce an integer it is really just a float still technically, but for all practical purposes when it comes to the product in a mathematical sense it is an integer. The parseInt method is often the first go to solution with this, and for the most part it will work just fine. However there are other was to parse a value to an integer, or float in javaScript as well, and there are subtle little edge cases that might come up in certain situations. Some of the other options to consider are the parseFloat method that will do more or less the same as parseInt only the return value will be a float, and there is also using the Number function to convert a string to a number also. So lets take a look at paserInt and also the options that come to mind when it comes to parsing values to integers in javaScript.

1 — parseInt basic examples

I assume that you have at least some background when it comes to the subject of getting started with javaScript. There are a number of ways to get started if you have not done so all ready and even if you have there are other ways to go about playing around with the basics other than the way that you might be familiar with thus far. When it comes to playing around with simple expressions often I can get away with just opening up the javaScript console in chrome as a way to do so for example.

Before I get into other ways to go about creating a integer value from a string in javaScript other then parseInt it would be a good idea to first cover the basics of parseInt, and how it works with a range of various examples of string values that might potential be passed to parseInt in a project. So for starters lets just take a look at some basic examples of using just the parseInt function only.

1.2 — A basic example of parseInt

A very basic example of parseInt might involve just passing a string of a number as the first argument when calling the parseInt function. The returned result will be a number rather than a string and if all goes well the value of the number will be the same of that of the string value. When called parseInt will attempt to parse what is passed to it as a number that will be an integer value, so I do not need to bother with rounding the result, more on rounding a little later So if for example I pass the string value of 42 the result will be a number with the value of 42 rather than a string of that number, also if I give a string value like 42.125 the result will again be f2

1.1 — parseInt will just cut a fraction from a number

There is the question of how parseInt will treat a fraction of a number, when it comes to the subject of rounding, or just cutting the fraction part of a number. With that said it would seem that parseInt will just cut the fraction part from the number value. If this is a problem then this would then be a reason why one would prefer to use one of the options for rounding numbers in place of using parseInt. Such as using the parseFloat method and then the Math.ceil, Math.round, or Math.floor methods.

1.3 — using a radix value for the second argument

The parseInt method in native core javaScript works by just passing a string of a number as the first argument, and an optional radix as the second argument. The default as one might expect is base 10 which is the radix system that many people are familiar with. The radix value applies to the given string value not the resulting return value, the return value will always be base 10.

1.4 — Wrong radix can result in NaN

There are a few reason why one might end up with a NaN value when using parseInt. One such reason why NaN might be the result is when it comes to strings that contain letters that are to be used with a certain radix, NaN can result if the proper radix is not given. For example say I have a string that contains a number but the radix is not 10, but 16, in other words a hex number. If I just pass the hex string to parseInt the result will be NaN because the default radix of 10 is what was used. If I pass the hex string as the first argument, and then set the proper radix of 16 as the second argument, then the desired number value will be returned.

1.5 — A starting char that is not used for number values can result in NaN

Be mindful of any characters that are not used at all for number values of any radix. If a char that is not part of a number is at then end of a string then the parseInt method will just ignore it, and work with any valid chars from the start of the string up to that index in the string. However if a string begins with a char that is not used even with the property radix for the rest of the values that will result in NaN. The parseInt method will not preform any kind of text pattern matching for you, you will need to do that before hand when it comes to extracting the desired input value for the parseInt function.

2 — Some things to look out for when using parseInt

Now that I have covered the basics of the parseInt method maybe now it is called for to take a deeper look at some of the things to be aware of when using the parseInt method. Although the parseInt method will work just fine in most cases, if a source string goes into notation that will result in NaN. Another thing to be mindful with parseInt, as well as javaScript numbers in general is what the deal is with max safe integer. So in this section I will be going over some weird things that might pop up when using parseInt, after this I can get to some alternatives to the parseInt method.

2.1 — parseInt converts to String first

The parseInt method might not always return expected results in some situations. One such situation is how parseInt will work when given a string of a javaScript number that makes use of notation with the letter e in it. For example the parseInt method converts to a string first and if it is a number then goes off into notation, then the letter e char will not be recognized as a number and will parse an int based on what comes before it.

So then this is one of the little things about parseInt that a javaScript developer should be ware of when making use of it when working with numbers that will go off into notation.

2.2 — The deal with max safe integer

There is also the nature of the max safe integer, when adding anything to that and going beyond the max safe int that too can result in unexpected results as well with parseInt. I Covered the basic idea of what max safe integer is on my post that has to do with JavaScript numbers in general that gets into this in detail.

If you need to work with very large numbers, and retain precision not only should you forget about using parseInt, you should forget about using javaScript numbers all together. There are libraries, and also some native stuff in the works to allow for a whole other way of preforming high precision math. However getting into that in detail would be off topic here.

3 — Alternatives to the parseInt method

The parseInt function will work just fine in most cases, however thus far I can not say that I use it often. I am not saying that using the parseInt method is bad practice it is just that there are alternatives that also work well. Also in some cases the alternatives will work better in some of those cases where the parseInt method will fall short, such as with using numbers that go into notation. Also I often like having a higher degree of control when it comes to how to handle the fraction part of a source string or number.

3.1 — The Number function

The Number function can be used to convert a string to a number also. It is a way to explicitly declare the the value that is given to the number function is th be parsed as a number. However it will not parse to an integer, at least not my itself, so it would have to be used in conjunction with an additional method such as the Math.round method.

3.2 — Multiply by a string of the number 1 and round to parse to an integer

ANother trick that comes to mind is multiply a value by a string of the number one, and then using something like Math.floor, or any other such method to round the result of that. The reason why this works is because of the typeless nature of javaScript. This sort of thing would not work with addition because that is used for both addition and string concatenation. So when it comes to using addition that would help to convert numbers to strings, and I see similar tricks to this being used as a way to parse numbers to strings. However when it comes to an operator such as multiplication that is something that is only a math operation, so the result is a number rather than a string.

3.3 — The valueOf method of an Object

When it comes to making any kind of object by way of creating a constructor function, or just a plain object literal I can define what a valueOf method should be for this kind of object. The return value of a valueOf method should be whatever the primitive value of the object should be. So then in the body of this valueOf method I can make it so that the primitive value that is returned is a number, and by any means make sure that the number is an integer.

3.4 — The parseFloat method

There is also the parseFloat function that will parse a string value into a number with the fraction part of the number. There is doing that, and then preforming any additional things that I want to do when it comes to rounding or cutting the decimal.

4 — Conclusion

So the javaScript parseInt method is one of several methods that can be used to parse a value to a number, there are also many other little ticks that can be used to parse a value to a number also. There is still the question of not just parsing to a number, but parsing to an integer rather than a float, and for that the parseInt method works just fine in most cases.

parseInt()

Функция parseInt() принимает строку в качестве аргумента и возвращает целое число в соответствии с указанным основанием системы счисления.

Интерактивный пример

Синтаксис

Параметры

Значение, которое необходимо проинтерпретировать. Если значение параметра string не принадлежит строковому типу, оно преобразуется в него (с помощью абстрактной операции ToString ). Пробелы в начале строки не учитываются.

Целое число в диапазоне между 2 и 36, представляющее собой основание системы счисления числовой строки string , описанной выше. В основном пользователи используют десятичную систему счисления и указывают 10. Всегда указывайте этот параметр, чтобы исключить ошибки считывания и гарантировать корректность исполнения и предсказуемость результата. Когда основание системы счисления не указано, разные реализации могут возвращать разные результаты.

Возвращаемое значение

Целое число, полученное парсингом (разбором и интерпретацией) переданной строки. Если первый символ не получилось сконвертировать в число, то возвращается NaN .

Описание

Функция parseInt преобразует первый переданный ей аргумент в строковый тип, интерпретирует его и возвращает целое число или значение NaN . Результат (если не NaN ) является целым числом и представляет собой первый аргумент ( string ), рассматривающийся как число в указанной системе счисления ( radix ). Например, основание 10 указывает на преобразование из десятичного числа, 8 — восьмеричного, 16 — шестнадцатеричного и так далее. Если основание больше 10 , то для обозначения цифр больше 9 используются буквы. Например, для шестнадцатеричных чисел (основание 16) используются буквы от A до F .

Если функция parseInt встречает символ, не являющийся числом в указанной системе счисления, она пропускает этот и все последующие символы (даже, если они подходящие) и возвращает целое число, преобразованное из части строки, предшествовавшей этому символу. parseInt отсекает дробную часть числа. Пробелы в начале и конце строки разрешены.

Так как некоторые числа включают символ e в своём строковом представлении (например, 6.022e23 ), то использование parseInt для усечения числовых значений может дать неожиданные результаты, когда используются очень малые или очень большие величины. parseInt не должна использоваться как замена для Math.floor() .

Если основание системы счисления имеет значение undefined (не определено) или равно 0 (или не указано), то JavaScript по умолчанию предполагает следующее:

  • Если значение входного параметра string начинается с » 0x » или » 0X «, за основание системы счисления принимается 16, и интерпретации подвергается оставшаяся часть строки.
  • Если значение входного параметра string начинается с «0», за основание системы счисления принимается либо 8, либо 10, в зависимости от конкретной реализации. В спецификации ECMAScript 5 прописано использование 10 (десятичная система), но это поддерживается ещё не всеми браузерами, поэтому необходимо всегда указывать основание системы счисления при использовании функцииparseInt .
  • Если значение входного параметра string начинается с любого другого символа, система счисления считается десятичной (основание 10).

Если первый символ строки не может быть преобразован в число, parseInt возвращает значение NaN .

С точки зрения математики, значение NaN не является числом в какой-либо системе счисления. Чтобы определить, вернёт ли parseInt значение NaN в качестве результата, можно вызвать функцию isNaN . Если NaN участвует в арифметических операциях, результатом также будет NaN .

JavaScript — parseInt()

Sanje Qi

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

Syntax

Parameters

string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored.

radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string . Be careful — this does not default to 10.

Return value: It returns a number and if the first character can’t be converted to a number then the function returns NaN. It actually returns a number parsed up to that point where it encounters a character which is not a number in the specified radix(base).
Example:

Description

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN .

If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix. (For example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.) For radices above 10 , letters of the English alphabet indicate numerals greater than 9 . For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix , it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Because some numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 × 1023), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor() .

If the radix is undefined , 0, or unspecified, JavaScript assumes the following:

  1. If the input string begins with "0x" or "0X" (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
  2. If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. For this reason always specify a radix when usingparseInt .
  3. If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseInt returns NaN unless the radix is bigger than 10.

For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN . If NaN is passed on to arithmetic operations, the operation result will also be NaN .

To convert a number to its string literal in a particular radix, use thatNumber.toString(radix) .

parseInt converts a BigInt to a Number and loses precision in the process because trailing non-numeric values, including "n", are discarded.

Name already in use

content / files / en-us / web / javascript / reference / global_objects / parseint / index.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

  • : A string starting with an integer. Leading <> in this argument is ignored.
  • : An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string . It is converted to a 32-bit integer; if it’s nonzero and outside the range of [2, 36] after conversion, the function will always return NaN . If 0 or not provided, the radix will be inferred based on string ‘s value. Be careful — this does not always default to 10 ! The description below explains in more detail what happens when radix is not provided.

An integer parsed from the given string , or <> when

  • the radix as a 32-bit integer is smaller than 2 or bigger than 36 , or
  • the first non-whitespace character cannot be converted to a number.

Note: JavaScript does not have the distinction of «floating point numbers» and «integers» on the language level. parseInt() and parseFloat() only differ in their parsing behavior, but not necessarily their return values. For example, parseInt(«42») and parseFloat(«42») would return the same value: a <> 42.

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN .

If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix . (For example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.)

The radix argument is converted to a number. If it’s unprovided, or if the value becomes 0, NaN or Infinity ( undefined is coerced to NaN ), JavaScript assumes the following:

  1. If the input string , with leading whitespace and possible + / — signs removed, begins with 0x or 0X (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexadecimal number.
  2. If the input string begins with any other value, the radix is 10 (decimal).

Note: Other prefixes like 0b , which are valid in number literals, are treated as normal digits by parseInt() . parseInt() does not treat strings beginning with a 0 character as octal values either. The only prefix that parseInt() recognizes is 0x or 0X for hexadecimal values — everything else is parsed as a decimal value if radix is missing.

If the radix is 16 , parseInt() allows the string to be optionally prefixed by 0x or 0X after the optional sign character ( + / — ).

If the radix value (coerced if necessary) is not in range [2, 36] (inclusive) parseInt returns NaN .

For radices above 10 , letters of the English alphabet indicate numerals greater than 9 . For example, for hexadecimal numbers (base 16 ), A through F are used. The letters are case-insensitive.

parseInt understands exactly two signs: + for positive, and — for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string.

If parseInt encounters a character that is not a numeral in the specified radix , it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although 1e3 technically encodes an integer (and will be correctly parsed to the integer 1000 by parseFloat() ), parseInt(«1e3», 10) returns 1 , because e is not a valid numeral in base 10. Because . is not a numeral either, the return value will always be an integer.

If the first character cannot be converted to a number with the radix in use, parseInt returns NaN . Leading whitespace is allowed.

For arithmetic purposes, the NaN value is not a number in any radix. You can call the Number.isNaN function to determine if the result of parseInt is NaN . If NaN is passed on to arithmetic operations, the operation result will also be NaN .

Because large numbers use the e character in their string representation (e.g. 6.022e23 for 6.022 × 10 23 ), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for <>.

To convert a number to its string literal in a particular radix, use thatNumber.toString(radix) .

Because parseInt() returns a number, it may suffer from loss of precision if the integer represented by the string is outside the safe range. The BigInt() function supports parsing integers of arbitrary length accurately, by returning a <>.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *