Справочник по javascript

parseInt and parseFloat

Numeric conversion using a plus or is strict. If a value is not exactly a number, it fails:

The sole exception is spaces at the beginning or at the end of the string, as they are ignored.

But in real life we often have values in units, like or in CSS. Also in many countries the currency symbol goes after the amount, so we have and would like to extract a numeric value out of that.

That’s what and are for.

They “read” a number from a string until they can’t. In case of an error, the gathered number is returned. The function returns an integer, whilst will return a floating-point number:

There are situations when will return . It happens when no digits could be read:

The second argument of

The function has an optional second parameter. It specifies the base of the numeral system, so can also parse strings of hex numbers, binary numbers and so on:

Description

Numbers provides a comprehensive set of mathematical tools that currently are not offered in JavaScript. These tools include:

  • Basic calculations
  • Calculus
  • Matrix Operations
  • Prime Numbers
  • Statistics
  • More…

A few things to note before using: JavaScript, like many languages, does not necessarily manage floating points as well as we’d all like it to. For example, if adding decimals, the addition tool won’t return the exact value. This is an unfortunate error. Precautions have been made to account for this. After including numbers, you can set an error bound. Anything in this will be considered an «acceptable outcome.»

The primary uses cases are client side operations which the DOM will recognize (e.g. 1.1px == 1px). It can be used for data analysis, calculations, etc. on the server as well.

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals:

But numbers can also be defined as objects with the keyword :

Example

var x = 123;
var y = new Number(123);
//
typeof x returns number
//
typeof y returns object

Do not create Number objects.
It slows down execution speed.The keyword complicates
the code. This can produce some unexpected results:

When using the operator, equal
numbers are equal:

Example

var x = 500;             
var y = new Number(500);
// (x == y) is true because x and y have equal values

When using the operator, equal numbers are not equal, because the operator expects equality in both type and value.

Example

var x = 500;             
var y = new Number(500);
// (x === y) is false because x and y have different types

Or even worse. Objects cannot be compared:

Example

var x = new Number(500);             
var y = new Number(500);
// (x == y) is false because objects cannot be compared

Note the difference between and .Comparing two JavaScript objects will always return .

❮ Previous
Next ❯

toString(base)

Метод возвращает строковое представление числа в системе счисления .

Например:

может варьироваться от до (по умолчанию ).

Часто используемые:

  • base=16 — для шестнадцатеричного представления цвета, кодировки символов и т.д., цифры могут быть или .

  • base=2 — обычно используется для отладки побитовых операций, цифры или .

  • base=36 — максимальное основание, цифры могут быть или . То есть, используется весь латинский алфавит для представления числа. Забавно, но можно использовать -разрядную систему счисления для получения короткого представления большого числового идентификатора. К примеру, для создания короткой ссылки. Для этого просто преобразуем его в -разрядную систему счисления:

Две точки для вызова метода

Внимание! Две точки в это не опечатка. Если нам надо вызвать метод непосредственно на числе, как в примере выше, то нам надо поставить две точки после числа

Если мы поставим одну точку: , тогда это будет ошибкой, поскольку синтаксис JavaScript предполагает, что после первой точки начинается десятичная часть. А если поставить две точки, то JavaScript понимает, что десятичная часть отсутствует, и начинается метод.

Также можно записать как .

Number Methods

Method Description
isFinite() Checks whether a value is a finite number
isInteger() Checks whether a value is an integer
isNaN() Checks whether a value is Number.NaN
isSafeInteger() Checks whether a value is a safe integer
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toLocaleString() Converts a number into a string, based on the locale settings
toPrecision(x) Formats a number to x length
toString() Converts a number to a string
valueOf() Returns the primitive value of a number

All number methods return a new value. They do not change the original
variable.

Объект Number

Последнее обновление: 1.11.2015

Объект Number представляет числа. Чтобы создать число, надо передать в конструктор Number число или стоку, представляющую число:

var x = new Number(34);
var y = new Number('34');
document.write(x+y); // 68

Определения x и y в данном случае будут практически аналогичны.

Однако создавать объект Number можно и просто присвоив переменной определенное число:

var z = 34;

Объект Number предоставляет ряд свойств и методов. Некоторые его свойства:

  • : наибольшее возможное число. Приблизительно равно 1.79E+308. Числа, которые больше этого значения, рассматриваются как Infinity

  • : наименьшее возможное положительное число. Приблизительно равно 5e-324 (где-то около нуля)

  • : специальное значение, которое указывает, что объект не является числом

  • : значение, которое обозначает отрицательную неопределенность и которое возникает при переполнении. Например, если мы складываем два
    отрицательных числа, которые по модулю равны Number.MAX_VALUE. Например:

    var x = -1 * Number.MAX_VALUE
    var y = -1 * Number.MAX_VALUE
    var z = x + y;
    if(z===Number.NEGATIVE_INFINITY)
    	document.write("отрицательная неопределенность");
    else
    	document.write(z);
    
  • : положительная неопределенность. Также, как и отрицательная неопределенность, возникает при переполнении,
    только теперь в положительную сторону:

    var x = Number.MAX_VALUE
    var y = Number.MAX_VALUE
    var z = x * y;
    if(z===Number.POSITIVE_INFINITY)
    	document.write("положительная неопределенность");
    else
    	document.write(z);
    

Некоторые основные методы:

  • : определяет, является ли объект числом. Если объект не является числом, то возвращается значение true:

    var a = Number.isNaN(Number.NaN); // true
    var b = Number.isNaN(true); // false - new Number(true) = 1
    var c = Number.isNaN(null);  // false - new Number(null) = 0
    var d = Number.isNaN(25);  // false
    var e = Number.isNaN("54"); // false
    

    Но следующее выражение вернет false, хотя значение не является числом:

    var f = Number.isNaN("hello"); // false
    

    Чтобы избежать подобных ситуаций, лучше применять глобальную функцию isNaN:

    var f = isNaN("hello"); // true
    
  • : преобразует строку в число с плавающей точкой. Например:

    var a = Number.parseFloat("34.90"); // 34.9
    document.write(a);
    var b = Number.parseFloat("hello"); // NaN
    document.write(b);
    var c = Number.parseFloat("34hello"); // 34
    document.write(c);
    
  • : преобразует строку в целое число. Например:

    var a = Number.parseInt("34.90"); // 34
    document.write(a);
    var b = Number.parseInt("hello"); // NaN
    document.write(b);
    var c = Number.parseInt("25hello"); // 25
    document.write(c);
    
  • : оставляет в числе с плавающей точкой определенное количество знаков в дробной части. Например:

    var a =  10 / 1.44;
    document.write("До метода toFixed(): " + a + "<br/>");
    a = a.toFixed(2); // оставляем два знака после запятой
    document.write("После метода toFixed(): " + a + "<br/>");
    

    Вывод браузера:

    До метода toFixed(): 6.944444444444445
    После метода toFixed(): 6.94
    

НазадВперед

MAX_VALUE & MIN_VALUE

The largest number possible to represent using the data type is 1.7976931348623157e+308 and it is represented by . The lowest number is .

1
2
3
4
5
6
7
8

console.log(Number.MAX_VALUE)

console.log(Number.MIN_VALUE)

 
******Output*****

1.7976931348623157e+308

5e-324

 

Numbers beyond Number. cannot be represented using the double-precision 64-bit binary system. Hence any value above the is truncated to the .

1
2
3
4
5
6

console.log(Number.MAX_VALUE+100==Number.MAX_VALUE);

 
//**output
//true
 

While the very large value results in

1
2
3
4
5
6

console.log(Number.MAX_VALUE+Number.MAX_VALUE);

 
**output

//Infinity
 

示例

使用 Number 对象给数字变量赋值

下例使用 对象的属性给几个数字变量赋值:

var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;

整数类型的范围

JavaScript 能够准确表示的整数范围在到之间(不含两个端点),超过这个范围,无法精确表示这个整数。 (详情请参阅 ECMAScript standard, chapter ):

var biggestInt = Number.MAX_SAFE_INTEGER; 
//9007199254740991
var smallestInt = Number.MIN_SAFE_INTEGER; 
//-9007199254740991

在解析序列化的JSON时,如果JSON解析器将它们强制转换为Number类型,那么超出此范围的整数值可能会被破坏。在工作中使用 类型代替,是一个可行的解决方案。

使用 转换 对象

下例使用 Number 作为函数来转换 对象为数字值:

var d = new Date("December 17, 1995 03:24:00");
print(Number(d));

这将输出 «819199440000»。

转换数字字符串为数字

Number('123')     // 123
Number('12.3')    // 12.3

Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

Adding Numbers and Strings

WARNING !!

JavaScript uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example

var x = 10;
var y = 20;
var z = x + y;           // z will be 30 (a number)

If you add two strings, the result will be a string concatenation:

Example

var x = «10»;
var y = «20»;
var z = x + y;           // z will be 1020 (a string)

If you add a number and a string, the result will be a string concatenation:

Example

var x = 10;
var y = «20»;
var z = x + y;           // z will be 1020 (a string)

If you add a string and a number, the result will be a string concatenation:

Example

var x = «10»;
var y = 20;
var z = x + y;           // z will be 1020 (a string)

A common mistake is to expect this result to be 30:

Example

var x = 10;
var y = 20;
var z = «The result is: » + x + y;

A common mistake is to expect this result to be 102030:

Example

var x = 10;
var y = 20;
var z = «30»;
var result = x + y + z;

The JavaScript interpreter works from left to right.

First 10 + 20 is added because x and y are both numbers.

Then 30 + «30» is concatenated because z is a string.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals:

But numbers can also be defined as objects with the keyword :

Example

var x = 123;
var y = new Number(123);
//
typeof x returns number
//
typeof y returns object

Do not create Number objects.
It slows down execution speed.The keyword complicates
the code. This can produce some unexpected results:

When using the operator, equal
numbers are equal:

Example

var x = 500;             
var y = new Number(500);
// (x == y) is true because x and y have equal values

When using the operator, equal numbers are not equal, because the operator expects equality in both type and value.

Example

var x = 500;             
var y = new Number(500);
// (x === y) is false because x and y have different types

Or even worse. Objects cannot be compared:

Example

var x = new Number(500);             
var y = new Number(500);
// (x == y) is false because objects cannot be compared

Note the difference between and .Comparing two JavaScript objects will always return .

JS Tutorial

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

parseInt и parseFloat

Для явного преобразования к числу можно использовать или . Если строка не является в точности числом, то результат будет :

Единственное исключение — это пробелы в начале строки и в конце, они игнорируются.

В реальной жизни мы часто сталкиваемся со значениями у которых есть единица измерения, например или в CSS. Также во множестве стран символ валюты записывается после номинала . Так как нам получить числовое значение из таких строк?

Для этого есть и .

Они «читают» число из строки. Если в процессе чтения возникает ошибка, они возвращают полученное до ошибки число. Функция возвращает целое число, а возвращает число с плавающей точкой:

Функции вернут , если не смогли прочитать ни одну цифру:

Второй аргумент

Функция имеет необязательный второй параметр. Он определяет систему счисления, таким образом может также читать строки с шестнадцатеричными числами, двоичными числами и т.д.:

toString(base)

The method returns a string representation of in the numeral system with the given .

For example:

The can vary from to . By default it’s .

Common use cases for this are:

  • base=16 is used for hex colors, character encodings etc, digits can be or .

  • base=2 is mostly for debugging bitwise operations, digits can be or .

  • base=36 is the maximum, digits can be or . The whole latin alphabet is used to represent a number. A funny, but useful case for is when we need to turn a long numeric identifier into something shorter, for example to make a short url. Can simply represent it in the numeral system with base :

Two dots to call a method

Please note that two dots in is not a typo. If we want to call a method directly on a number, like in the example above, then we need to place two dots after it.

If we placed a single dot: , then there would be an error, because JavaScript syntax implies the decimal part after the first dot. And if we place one more dot, then JavaScript knows that the decimal part is empty and now goes the method.

Also could write .

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

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

Adblock
detector