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 经典实例:第三版
82
3
如果你想四舍五入小数点左侧的部分(例如,四舍五入到最近的十、百等),
numberOfDecimalPlaces
使用负数即可。例如,
-1
四舍五入为最近的
10
-2
四舍五
入为最近的
100
等。
3.3.3
讨论
Math
对象有几个静态方法可以把小数值变成整数。
floor()
方法去掉所有小数,向
下四舍五入为最近的整数。
ceil()
方法则反过来,把小数向上四舍五入为下一个整
数。
round()
方法四舍五入到最近的整数。
关于
round()
方法,有两点要注意。
如果恰好是
0.5
,则向上四舍五入,尽管距前后两个整数的距离相等。在金融和
科学领域,经常使用不同的四舍五入技术来消除这种偏差(例如,同样是
0.5
有时向上四舍五入,有时向下四舍五入)。但是,如果你想在
JavaScript
中使用
这种行为,需要自己动手实现或者使用第三方库。
四舍五入负数时,
JavaScript
-0.5
向上四舍五入为零。这意味着,
-4.5
四舍五
入为
-4
,这与很多其他编程语言对四舍五入的实现有所不同。
3.3.4
参考
有时,四舍五入数字是为了让数值更接近适合显示的格式。如果你是想向用户显示
一个数字而四舍五入,或许会对
Number
对象的格式化方法感兴趣,详见
2.2
节。
3.4
保留小数的精确度
3.4.1
问题
JavaScript
中,所有数字都是浮点值,在某些操作中会出现微小的舍入误差。某
些时候(例如处理金额时),这种误差是不可接受的。
数字
83
3.4.2
方案
浮点舍入误差是一个众所周知的现象,几乎所有编程语言都有。例如, ...
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 Patterns

JavaScript Patterns

Stoyan Stefanov
JavaScript

JavaScript

David Flanagan
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9787519869601