在没有科学记数法的情况下在C ++中格式化有效数字 [英] Formatting n significant digits in C++ without scientific notation

查看:188
本文介绍了在没有科学记数法的情况下在C ++中格式化有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个浮点值格式化为n个有效数字,但从来没有使用科学记数法(即使它会更短)。
$ b $ <格式说明%f 不会显示有效数字,而%g 有时会给我科学记数法(这对我来说是不合适的) 。



我想以123,12.3,1.23或0.000000123



使用 C ++或boost 是否有优雅的方式

解决方案

我知道的最好的方法是在我自己的代码中使用它

pre > #include< string>
#include< math.h>
#include< sstream>
#include< iomanip>

int round(double number)
{
return(number> = 0)? (int)(number + 0.5):(int)(number - 0.5);

$ b std :: string格式(double f,int n)
{
if(f == 0){
return0 ;
}
int d =(int):: ceil(:: log10(f <0?-f:f)); / *小数点前的数字* /
double order = :: pow(10。,n - d);
std :: stringstream ss;
ss<< std :: fixed<< std :: setprecision(std :: max(n - d,0))<<<四舍五入(f *次序)/次序;
返回ss.str();




$ b $ c $ 11有std :: round,所以你不需要我的版本与新的编译器。

我在这里利用的技巧是通过以10个基本日志来计算小数点,然后从你想要的精度中减去它。
$ b $ p满足@Mats Petersson的要求,所以在任何情况下都可以工作。

我不喜欢的是初始检查零(所以日志功能不会炸毁)。建议改进/直接编辑这个答案最受欢迎。


I want to format a floating point value to n significant digits but never using scientific notation (even if it would be shorter).

The format specification %f doesn't deal in significant digits, and %g will sometimes give me scientific notation (which is inappropriate for my use).

I want values in the form "123", "12.3", "1.23" or "0.000000123".

Is there an elegant way to do this using C++ or boost?

解决方案

The best way I know (and use it in my own code) is

#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 has std::round so you won't need my version of with a new compiler.

The trick I'm exploiting here is to get the precision you want by taking the base 10 log to count the number of digits before the decimal and subtracting this from the precision you want.

It satisfies @Mats Petersson's requirement too, so will work in all cases.

The bit I don't like is the initial check for zero (so the log function doesn't blow up). Suggestions for improvement / direct editing of this answer most welcome.

这篇关于在没有科学记数法的情况下在C ++中格式化有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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