Tag: 重要数字

如何将浮点数舍入到Ruby中指定数量的有效数字?

在Ruby中拥有等效的R的signif函数会很不错。 例如: >> (11.11).signif(1) 10 >> (22.22).signif(2) 22 >> (3.333).signif(2) 3.3 >> (4.4).signif(3) 4.4 # It’s usually 4.40 but that’s OK. R does not print the trailing 0’s # because it returns the float data type. For Ruby we want the same. >> (5.55).signif(2) 5.6