Round number to specified number of digits

余生颓废 提交于 2020-01-01 01:17:09

问题


Is there a simple function to round a Double or Float to a specified number of digits? I've searched here and on Hoogle (for (Fractional a) => Int -> a -> a), but haven't found anything.


回答1:


Not sure whether any standard function exists, but you can do it this way:

 (fromInteger $ round $ f * (10^n)) / (10.0^^n)



回答2:


It depends on what you are going to do with the rounded number.

If you want to use it in calculations, you should use Data.Decimal from Decimal library.

If you want just to format the number nicely, you should use Text.Printf from the standard library (base package).




回答3:


λ: ((/100) $ fromIntegral $ round (0.006 * 100)) == 0.006
λ: False

λ: ((/100) $ fromIntegral $ round (0.06 * 100)) == 0.06
λ: True


来源:https://stackoverflow.com/questions/12450501/round-number-to-specified-number-of-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!