双到字符串用指数表示的大数字的转换

Double to String Conversion of large numbers with exponential

本文关键字:数字 转换 表示 指数 字符串      更新时间:2023-10-16

我有一个应用程序,其中我必须处理非常大的数字。应用程序API给了我编号,然后我不得不将其转换为字符串并发送到进一步处理。代码接收号码为-153562179.1619387

然后对于转换,我使用了-

char buffer[255];
sprintf(buffer, "%e", OverallVolume); //OverallVolume has the above value.

现在,缓冲区变量返回1.535625e+009,标准化为1535625000.00但我的应用程序显示值为1.5356252e+09,标准化为1535625200.00

所以我想问我应该使用什么方法将Double转换为String,这样我得到的值将与应用程序显示的值相匹配。

如果我正确理解你的问题,你希望小数点后出现7位数字。为此,指定精度如下:

sprintf(buffer, "%.7e", OverallVolume); // buffer contains 1.5356252e+09

现场演示


此外,由于它被标记为C++,因此这里有一个使用IO流的版本,可以打印相同的结果。

#include <ios>
#include <iomanip>
#include <iostream>
#include <sstream>
int main() 
{
double OverallVolume = 1535625179.1619387;
std::ostringstream ss;
ss << std::scientific << std::setprecision(7) << OverallVolume;
std::cout << ss.str() << 'n'; // prints 1.5356252e+09
}

现场演示