如何将双精度舍入到小数点后n位? [英] how to round a double to n decimals?

查看:93
本文介绍了如何将双精度舍入到小数点后n位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在标准库中找到一个舍入函数,但是没有看到一个.有什么办法可以在C ++中将小数点后两位取整到n?

I am trying to find a round function in the standard library but I didn't see one. Is there any way to round a double to n decimals in c++?

推荐答案

C ++ 11具有

C++11 has std::round in <cmath>.

如果没有,您可以在调整后的数字上使用std :: floor和std :: ceil.例如. std::floor(n * 100 + 0.5)/100舍入到小数点后两位.

Without that you can use std::floor and std::ceil on adjusted numbers. E.g. std::floor(n * 100 + 0.5)/100 to round to two decimal places.

尽管应该注意的是,舍入并不是完全无关紧要的.有一些复杂性,例如选择向零舍入,向负无穷大舍入,向偶数舍入等.如果要编写用于生产的程序,请确保您了解域的舍入要求.

Although it should be noted that rounding isn't entirely trivial; There are complications such as choosing to round toward zero, toward negative infinity, round to even, etc. If you're writing programs for production be sure you understand the rounding requirements for your domain.

这篇关于如何将双精度舍入到小数点后n位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆