已更新:
我一直在尝试可以在stackoverflow中找到的所有方法,但仍然找不到解决方案。
我的意思是,我有一个字符串“ 23.46”,并且无论如何要将其转换为double或float。这是为了在另一个库中使用。
但是无论我如何转换,地板,* 100,添加,四舍五入,它总是给我24.4600000001之类的东西。
我知道传输时存在一些精度问题。但是我确实需要一种方法给我一个精确地为d = 24.46的两倍的数字。
================================================ =============================== 我有很多字符串值,其中有些是经过转换的精度为double的值,如下所示:
char pt[100];
sprintf(pt, "%.2lf", i);
return string(pt);
现在,在代码的另一端,我需要将字符串转换回双精度,但是我尝试使用strtod和atof来降低精度。
我的问题是:
什么是检查字符串是否可以是双精度的好方法?
如何以给定的精度将字符串转换回double?我只需要%.2lf
就可以像这样:
0.21, 35.45, ...
非常感谢!
答案 0 :(得分:-1)
鉴于您说使用std::strtod
并不能解决问题,可以使用stringstreams将字符串解析为双精度,也可以使用其标志来断言字符串的内容是否可转换
下面是一个带有一些来回转换的示例,并检查整个字符串(而不只是其中的一些数字)是否可以解析为double:
#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
std::string str = "23.4k7"; //string with a character in the middle
std::istringstream ss(str); //put string in a stream
double num;
ss >> num; //convert string to double
if(!ss.fail() && ss.eof()) { //check if the whole string is parseable
std::cout << "is parseable" << std::endl;
}
else {
std::cout << "is not parseable";
return EXIT_FAILURE;
}
std::stringstream to_num;
to_num << std::fixed << std::setprecision(2) << num; //double to string 2 decimal places
std::cout << to_num.str();
to_num >> num; //final conversion to double
}
由于字符串中包含字母字符,因此将输出:
is not parseable
但是,如果您使用有效数字,它将输出转换后的值:
字符串str:
234.2345
输出:
is parseable
234.23
请注意,您可以使用
if(ss >> num)
std::cout << "is parseable";
但是,这有一个弱点,例如,如果您解析了123.45rt56
,123.45
,它将仍然解析,其余的将按照示例代码中的方式丢弃,如果字符串包含任何字符,则将返回错误。您可以根据自己的需要选择更合适的方式。