Math.round()
Math.round()
静态方法返回四舍五入到最接近整数的数字值。
¥The Math.round()
static method returns the value of a number rounded to the nearest integer.
Try it
语法
参数
返回值
描述
¥Description
如果参数的小数部分大于 0.5,则参数将四舍五入为具有下一个较高绝对值的整数。如果小于 0.5,则参数四舍五入为绝对值较小的整数。如果小数部分恰好为 0.5,则参数将按 +∞ 方向四舍五入到下一个整数。
¥If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.
注意:这与许多语言的
round()
函数不同,后者通常从零开始舍入半增量,在小数部分恰好为 0.5 的负数情况下给出不同的结果。¥Note: This differs from many languages'
round()
functions, which often round half-increments away from zero, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.
Math.round(x)
与 Math.floor(x + 0.5)
并不完全相同。当 x
为 -0 或 -0.5 ≤ x < 0 时,Math.round(x)
返回 -0,而 Math.floor(x + 0.5)
返回 0。然而,忽略差异和潜在的精度误差,Math.round(x)
和 Math.floor(x + 0.5)
通常是等效的。
¥Math.round(x)
is not exactly the same as Math.floor(x + 0.5)
. When x
is -0, or -0.5 ≤ x < 0, Math.round(x)
returns -0, while Math.floor(x + 0.5)
returns 0. However, neglecting that difference and potential precision errors, Math.round(x)
and Math.floor(x + 0.5)
are generally equivalent.
因为 round()
是 Math
的静态方法,所以你始终将其用作 Math.round()
,而不是用作你创建的 Math
对象的方法(Math
没有构造函数)。
¥Because round()
is a static method of Math
, you always use it as Math.round()
, rather than as a method of a Math
object you created (Math
has no constructor).
示例
使用圆形
规范
Specification |
---|
ECMAScript Language Specification # sec-math.round |
浏览器兼容性
BCD tables only load in the browser