我想将浮点值格式化为n个有效数字,但从不使用科学计数法(即使它会更短)。
格式规范%f
不会处理有效数字,并且%g
有时会给我科学的记号(不适合我使用)。
我想要"123", "12.3", "1.23" or "0.000000123"
形式的值。
有没有优雅的方式可以使用 C++或增强来做到这一点?
最佳答案
我知道(并在我自己的代码中使用它)的最好方法是
#include <string>
#include <math.h>
#include <sstream>
#include <iomanip>
int round(double number)
{
return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}
std::string format(double f, int n)
{
if (f == 0) {
return "0";
}
int d = (int)::ceil(::log10(f < 0 ? -f : f)); /*digits before decimal point*/
double order = ::pow(10., n - d);
std::stringstream ss;
ss << std::fixed << std::setprecision(std::max(n - d, 0)) << round(f * order) / order;
return ss.str();
}
c++ 11具有std::round,因此您不需要使用新版本的我的编译器。
我在这里利用的技巧是,通过以10为底的对数来计算小数点前的位数,并从所需的精度中减去该位数,从而获得所需的精度。
它也满足@Mats Petersson的要求,因此在所有情况下都可以使用。
我不喜欢的是初始检查是否为零(因此log函数不会崩溃)。改进建议/直接编辑此答案非常受欢迎。
关于c++ - 不使用科学记数法在C++中格式化n个有效数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17211122/