Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
84
3
3.4.3
讨论
出现浮点舍入误差的根源在于,有些小数值不四舍五入无法使用二进制表示。十进
制计数制也有这个问题(你可以计算
1/3
的结果试试)。浮点数的不同在于,舍入
误差不符合直觉。在我们的设想中,
0.1
0.2
不会出问题,毕竟这两个小数在十进
制中都可以准确表示。
其他编程语言也有类似的现象,不过很多语言都为小数或金额提供了专门的数据类
型。
JavaScript
没有。但是,已经有新增
Decimal
类型的提案(
https://github.com/
tc39/proposal-decimal
),未来可能会加入
JavaScript
语言的新版中。
3.4.4
参考
如果你经常做财务计算,简单起见,可以使用第三方库,例如
bignumber.js
https://
github.com/MikeMcl/bignumber.js
)。这个库提供了一个自定义的数字数据类型,使
用上与普通的
Number
类型差不多,但是能保留固定的小数位,完全保持精度。
3.5
把字符串转换成数字
3.5.1
问题
你想解析字符串中的数字,把它转换成数字数据类型。
3.5.2
方案
把数字转换成字符串肯定不会失败。反过来,把字符串转换成数字做运算,就不那
么容易了。
公认有效的方法是使用
Number()
函数。
const
stringData = '42';
const
numberData = Number(stringData);
Number()
函数不能识别货币符号和逗号分隔符等格式,但允许字符串首尾有空格。
数字
85
如果是空字符串, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript

JavaScript

T. J. Crowder
JavaScript

JavaScript

David Flanagan
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9787519869601