Home  >  Article  >  Web Front-end  >  Master JavaScript numeric types in one article

Master JavaScript numeric types in one article

WBOY
WBOYforward
2022-05-30 19:03:112442browse

This article brings you relevant knowledge about javascript, which mainly introduces the relevant content about number types. There are two types of numbers in JavaScript: Number and BigInt types, as follows Let's take a look, I hope it will be helpful to everyone.

Master JavaScript numeric types in one article

【Related recommendations: javascript video tutorial, web front-end

JavaScript## There are two types of numbers in #:

  1. Number type, which is the number type in the conventional sense, with 64 bits IEEE-754 format storage, which belongs to "double precision floating point number". Up to now, all the numbers we have come into contact with are of type Number;
  2. BigInt Type, representing integers of any length. Normally we do not use them, unless they represent numbers other than 253 to -253. We will use such professional data types in The following chapters will introduce it in detail;
How to write numbers

The way to write numbers is very simple, but

JavaScrpt has a lot of convenient and fast syntactic sugar for us to use, Learning these syntactic sugars well can not only improve our code reading ability, but also improve the high-level sense of our code.

Separator

Decimal numbers are the simplest. We will use them more or less in almost every article. For example, we create a variable and store

100 billion:

let tenbillion = 10000000000;
Although the operation is very simple, there is a problem: it is difficult to count how many

0 are behind 1. If we The code I write is a transfer code. If you make a mistake with 0, you may lose everything.

At this time, we can use

_ as the separator, as follows:

let tenbillion = 10_000_000_000;
The above code can clearly count the individuals of

0 number, is obviously the optimal solution!

The underscore here

_ is a syntax sugar for JavaScript, which will be ignored by the engine during execution. The above two writing methods have the same effect, but the reading experience is different. Very big.

Qingqi Brain Circuit

Some children’s shoes have to be asked. I have always been

40 since I was a child. Yes, why do we have to divide 30 into a group? Therefore, we can write it in the following way, and there is no problem:

let tenbillion = 100_0000_0000;
Or we can write it like this:

let tenbillion = 1_0000_0000_00;
What I want to express here is that no matter which segmentation method you use, it is not If it affects the size of the number itself, think of the most powerful way!

Omitted 0

Although using

_ can elegantly divide many 0, in real life, we generally do not write this way, for example We often write 10000000000 as "10 billion", so that we can omit a lot of 0, thus reducing the possibility of making mistakes.

JavaScript also provides a way to omit 0. We can use the letters e followed by a number to represent 0## The number of #, for example: <pre class="brush:php;toolbar:false">let tenbillion = 1e10;//100亿,1后面10个0console.log(3.14e9);//3140000000,后面7个0,此处疑惑可往下看</pre> The understanding of the above code is very simple,

e10

can be understood as 1_0000_0000_00, which is 1 Behind it are 10 0, so we can think: <pre class="brush:php;toolbar:false">1e10 === 1 * 1_0000_0000_00;//e10表示1后面10个03.14e9 === 3.14 * 1_000_000_000;//e9表示1后面9个0</pre> We can also use this method to represent very small numbers, such as

1

Nano: <pre class="brush:php;toolbar:false">let nm = 0.000000001;//单位(米)</pre> Since there are too many

0

, we can also use _ to divide: <pre class="brush:php;toolbar:false">let nm = 0.000_000_001;</pre>Of course, we can also use

e

omit all 0, as follows: <pre class="brush:php;toolbar:false">let nm = 1e-9;//1的左边9个0,包括小数点前面的那个</pre>In other words,

e-9

means 1-9, that is, 1/1000_000_000, so the following equation is true: <pre class="brush:php;toolbar:false">1e-9 === 1 / 1_000_000_000;3.14e-8 === 3.14 / 1_000_000_00;</pre>16, 8, binary

Hexadecimal is used in programming For commonly used formats, such as color, encoding, etc., we can add

0x

before ordinary numbers to represent hexadecimal numbers: <pre class="brush:php;toolbar:false">let hex = 0xff;//255,不区分大小写,0xFF是一样的</pre> Use

0b

for binary numbers. Beginning: <pre class="brush:php;toolbar:false">let bin = 0b1011;//11</pre> Octal numbers start with

0o

: <pre class="brush:php;toolbar:false">let oct = 0o777;//511</pre> This simple writing method only supports these three special types. As for other base numbers, you can use special Function generation (

parseInt

). toString(base)

toString

method can convert numbers into string format corresponding to base base. For example:

let num = 996;
console.log(num.toString(8));//转为8进制字符串
console.log(num.toString(16));//转为16进制字符串
console.log(num.toString(32));//转为32进制字符串

The code execution result is as follows:

Master JavaScript numeric types in one article

The range of base

can be from 2 to 36, if not filled in, the default is 10. Note that if you use numbers to directly call the

toString

method, in some cases you need to apply two ., for example: <pre class="brush:php;toolbar:false">console.log(123.toString(8));//Error,语法错误console.log(123..toString(8));//正确,173</pre> <p>数字后面有两个<code>.,这是因为在JavaScript中数字后面的第一个.被认为是小数点,第二个点才是调用函数的.

如果是小数就不存在这个问题,举个栗子:

console.log(3.14.toString(8));

亦或者,我们使用小括号可以避免使用两个点,举个栗子:

console.log((123).toString(8));//'173

舍入

舍入是数字最常用的操作之一,通常包括:

  1. 向下取整,Math.floor(num)

    console.log(Math.floor(3.14));//3
    console.log(Math.floor(9.99));//9
    console.log(Math.floor(-3.14));//-4
    console.log(Math.floor(-9.99));//-10

    不遵循四舍五入原则,直接取小于等于当前数值的最近整数。

  2. 向上取整,Math.ceil(num)

    console.log(Math.ceil(3.14));//4
    console.log(Math.ceil(9.99));//10
    console.log(Math.ceil(-3.14));//-3
    console.log(Math.ceil(-9.99));//-9

    不遵循四舍五入原则,直接取大于等于当前数字的最近整数。

  3. 就近取整,Math.round(num)

    console.log(Math.round(3.14));//3
    console.log(Math.round(9.99));//10
    console.log(Math.round(-3.14));//-3
    console.log(Math.round(-9.99));//-10

    遵循四舍五入原则,取距离当前数字最近的整数。

  4. 移除小数,Math.trunc(num)

    console.log(Math.trunc(3.14));//3
    console.log(Math.trunc(9.99));//9
    console.log(Math.trunc(-3.14));//-3
    console.log(Math.trunc(-9.99));//-9

    直接移除小数点后面的数字,取整数位。IE浏览器不支持这个方法

对比以上四种方法:


Math.floor Math.ceil Math.round Math.trunc
3.14 3 4 3 3
9.99 9 10 10 9
-3.14 -4 -3 -3 -3
-9.99 -10 -9 -10 -9

精度

上述方法只是简单的把小数舍入成了整数,在有些情况下,我们需要特定精度的小数,例如取圆周率后4位应该怎么办呢?

有两种方法:

  1. 数学乘除计数

    let pi = 3.1415926;console.log(Math.round(pi * 10000) / 10000);//3.1416

    上述代码先将pi乘以10000,然后取整,再除以10000,从而得到了符合精度要求的结果。但是,这么做看起啦呆呆的,JavaScript为我们提供了更简单的方法。

  2. toFixed(n)

    let pi = 3.1415926;console.log(pi.toFixed(4));//3.1416

    以上代码看起来输出上没有什么问题,实际上,toFixed返回的是一个字符串,如果我们需要一个数字类型,要转换一下才行,可以使用单目运算符+ pi.toFixed(4)

    此外,如果小数的尾数长度不够,toFixed会在后面补上'0':

    let num = 3.1;console.log(num.toFixed(9));

    代码执行结果如下:
    Master JavaScript numeric types in one article
    这也侧面证明了toFixed的返回值是一个字符串,否则0会被省略。

偏差

浮点数表示在很多情况下总是存在偏差

在计算机内部,浮点数根据IEEE-754标准进行表示,其中单精度浮点数32位,双精度浮点数64位。在双精度浮点数中,1位用于表示符号,52位用于存储有效数字,11位存储小数点的位置。

偏差现象

虽然64位已经可以表示非常大的数字了,但是仍然存在越界的可能,例如:

let bigNum = 1e999;console.log(bigNum);//Infinity

越过做最大值的数字将变为Infinity(无穷),这样就丢失了原有数字的大小,属于偏差的一种。

还有一种偏差,需要我们学习:

console.log(0.1+0.2 === 0.3);//falseconsole.log(0.1 + 0.2);

代码执行结果如下:

Master JavaScript numeric types in one article

没错,0.1 + 0.2的结果并不是0.3,而是一堆0后面加个4

这种偏差是非常致命的,尤其在商城、银行工作场景中,即使是一个非常小的偏差,在高流水场景下都会丢失无尽的财富。

曾经听说过一个银行员工通过克扣工人工资,盗取百万财富的故事,每个员工的工资只克扣2毛!

我想这种事情发生在我身上,我肯定发现不了,所以无时无刻的精确是多么的重要。

这个故事不知真假~~

偏差原因

先以我们常见的十进制为例,我们都知道,小数中存在两个奇葩,一个叫无限循环小数,另一个叫无限不循环小数,例如1/3就是一个无限循环小数0.3333333(3),而圆周率就是一个无限不循环小数。无限就意味着无法用数字清楚的描述这个数字的大小,我们能写出来的都是不精确的。

二进制同样存在一些无限循环的数字,不同的是在十进制中0.1这种看起啦很简单的数字,在二进制中却是无限循环小数。

举个例子:

let x = 0.1;console.log(x.toFixed(20));

代码执行结果如下:

Master JavaScript numeric types in one article

是不是觉得不可思议呢?我们只是简单的创建了一个变量并赋值0.1,然后取小数点后20位,却得到了一个匪夷所思的结果。

如果我们换一个角度或许会更容易理解这种现象,在十进制中,任何整数除以10或者10整数次幂都是正常的精确的数字,例如1/10或者996/1000。但是,如果以3为除数,就会得到循环的结果,例如1/3

这种描述如果换到二进制上,同样是成立的。

在二进制中,任何整数除以2或者2的整数次幂都是正常的精确的数字,但是,如果以10为除数,就会得到无限循环的二进制数。

所以,我们就可以得出结论,二进制数字无法精确表示0.10.2就像十进制没有办法描述1/3一样。

注意:

这种数据上的偏差并非JavaScript的缺陷,像PHP、Java、C、Perl、Ruby都是同样的结果。

解决方法

  1. 舍入

    在展示一个无限循环小数的时候,我们可以直接使用toFixed方法对小数进行舍入,该方法直接返回字符串,非常方便用于展示价格。

    0.3.toFixed(2);//0.30
  2. 使用小单位

    另外一种方式是,我们可以使用较小的单位计算诸如价格、距离,例如采用分而不是元计算总价,实际上很多交易网站都是这么做的。但是这种方法只是降低小数出现的次数,并没有办法完全避免小数的出现。

Infinity、NaN

JavaScript数字中有两个特殊值:InfinityNaN

如何判断一个数字是不是正常数字呢?

我们可以使用两个方法:

  1. isFinite(val)
    该函数会将参数val转为数字类型,然后判断这个数字是否是有穷的,当数字不是NaNInfinity-Infinity时返回true
    console.log(isFinite(NaN));//falseconsole.log(isFinite(Infinity));//falseconsole.log(isFinite(3));//trueconsole.log(isFinite('12'));//true
    代码执行结果如下:
    Master JavaScript numeric types in one article
    由于无法转为数字的字符串会被转为NaN,所以我们可以使用isFinite方法判断字符串是不是数字串:
    console.log(isFinite('xxxx'));//falseconsole.log(isFinite('Infinite'));//falseconsole.log(isFinite(' '));//true,空串转为0
    代码执行结果如下:

Master JavaScript numeric types in one article

  1. isNaN(val)
    valNaN或者无法转为数字的其他值时,返回true
    console.log(isNaN(NaN));//trueconsole.log(isNaN('Infinite'));//true
    代码执行结果:
    Master JavaScript numeric types in one article
    为什么要使用isNaN函数而不是直接判读呢?
    例如:
    console.log(NaN === NaN);//false
    代码执行结果如下:
    Master JavaScript numeric types in one article
    这是因为NaN不等于任何数,包括自身。

Object.is

Object.is(a,b)可以判断参数ab是否相等,若相等返回true,否则返回false,它的结果只有三种情况:

  1. 可以比较NaN

    console.log(Object.is(NaN,NaN));//true

    代码执行结果:

    Master JavaScript numeric types in one article

  2. 0 和 -0

    console.log(Object.is(0,-0));//false

    代码执行结果:

    Master JavaScript numeric types in one article

    在计算机内部,正负使用01表示,由于符号不同,导致0-0实际上是不同的,二者的表示方式也不一样。

  3. 其他
     其他比较情况和a === b完全相同。

parseInt、parseFloat

parseIntparseFloat可以把字符串转为数字,与+Number不同的是,二者的限制更为松散。例如,像"100¥"这样的字符串使用+Number必然返回NaN,而parseIntparseFloat却能轻松应对。

举个例子:

console.log(+"100¥");console.log(parseInt("100¥"));console.log(parseFloat("12.5¥"));

代码执行结果:

Master JavaScript numeric types in one article

parseIntparseFloat会从字符串中读取数字,直到无法读取为止。二者特别适合处理像"99px""11.4em"这种数字开头的字符串情况,但是对于其他字符开头的字符串则返回NaN

console.log(parseInt('ff2000'));//NaN

但是,我们发现ff2000实际上是一个十六进制的数字字符串,parseInt同样可以处理这种情况,不过需要添加一个进制参数。

举个例子:

console.log(parseInt('FF2000',16));
//16719872
console.log(parseInt('0xFF2000',16));
//16719872
console.log(parseInt('nnnnnn',36));
//1430456963

代码执行结果:

Master JavaScript numeric types in one article

Math对象

内置的Math对象中包含了许多我们经常用到的常量和方法,以下仅举例介绍常用的几个:

  1. Math.PI

    圆周率Π是一个无限不循环的常量,我们可以使用Math.PI代替:

    console.log(Math.PI);

    Master JavaScript numeric types in one article

  2. Math.random()
    生成一个位于区间[0,1)的随机数:

    console.log(Math.random());console.log(Math.random());

Master JavaScript numeric types in one article
如果我们需要一个特定区间内的随机数,可以乘以特定的值,然后取整哦。

  1. Math.pow(a,b)

    计算ab,举例如下:

    console.log(Math.pow(2,3));//8
  2. Math.max()/Math.min()

    从任意数量的参数中选出一个最大/最小值:

    console.log(Math.max(1,2,3,4,5));//5console.log(Math.min(1,2,3,4,5));//1

Master JavaScript numeric types in one article

【相关推荐:javascript视频教程web前端

The above is the detailed content of Master JavaScript numeric types in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete