Ruby format 保留的两位小数,是五舍六入?

liuminhan · January 06, 2020 · Last by huobazi replied at January 08, 2020 · 4687 hits

使用 format('%.2f', 4.565) 保留两位小数跟 4.565.round(2).to_s 的结果不一样

format('%.2f', 4.565) => 4.56
format('%.2f', 4.566) => 4.57

 4.565.round(2)  =>  4.57
 4.566.round(2) =>  4.57

四舍五入在大量的数据处理之后会导致结果偏大,format 有可能是使用的银行舍入法,四舍六入,五看上一位,奇进偶不进。 4.565 的第二位是偶数,所以不进 1,4.575 的结果的 format 的结果就是 4.58。

原来如此,了解了

You need to Sign in before reply, if you don't have an account, please Sign up first.