策略
Directed Rounding to an integer
定向舍入
原始值x到舍入值y的舍入方向是固定的:指向或远离限制值(0 或 +-无穷大)
1
y=f(x)
Round up
up 有两种解释
toward positive infinity
向正无穷取整
JS Math.ceil
23.5 gets rounded to 24, and −23.5 gets rounded to −23
away from zero
远离零取整(向无穷取整)
23.2 gets rounded to 24, and −23.2 gets rounded to −24
Big.roundUp
Round down
down 有两种解释
toward negative infinity
向负无穷取整
JS Math.floor
23.5 gets rounded to 23, and −23.5 gets rounded to −24
towards zero
向零取整
23.7 gets rounded to 23, and −23.7 gets rounded to −23
Big.roundDown
Rounding to the nearest integer
四舍六入五判断方向
- 小数部分是0.5时,不同的策略有不同的舍入方向
- 通常说的四舍五入采用的策略应该是 Round half up toward positive infinity
Round half up
有两种不同的解释
toward positive infinity
如果距离两个整数的距离相等,则向正无穷方向取整
23.5 gets rounded to 24, and −23.5 gets rounded to −24.
JS Math.round
JS中的 Math.round 采用该策略
1 | Math.round(-Infinity); // -Infinity |
away from zero
Rounds towards nearest neighbour. If equidistant, rounds away from zero
Big.roundHalfUp
1 | > big(-23.5).round().toString() |
PG numeric#round
1 | d72=# select round(-23.5::numeric); |
Round half down
Round half to odd
如果距离两个整数的距离相等,则取奇数
+23.5 becomes +23, as does +22.5
−23.5 becomes −23, as does −22.5
Round half to even
Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour.
如果距离两个整数的距离相等,则取偶数
0.245 舍入为 0.24
+23.5 becomes +24, as does +24.5; −23.5 becomes −24, as does −24.5.
银行家舍入法 Banker’s round
四舍六入五取偶
0.5 rounds down to 0; 1.5 rounds up to 2
IEEE 754标准规定的小数舍入标准
取最接近的整数,如果有两个最接近的整数,取偶数
舍入位的数值小于5时舍去
舍入位的数值大于6时进一
舍入位的数值等于5时,前位数为奇数,则进一得偶数,前位数为偶数,则舍去留偶数
PG real/double precision#round
1 | d72=# select round(-24.5::real); |