货币转换格式字符串倍增
问题描述:
什么是格式化字符串货币转换为双打货币转换格式字符串倍增
例如,最简单的方法,以1,234,567.00 1234567.00
字符串与字符串流结合取而代之的是我最好的选择至今。
我不是C++ 11呢。所以,http://en.cppreference.com/w/cpp/io/manip/get_money是不是一种选择
答
可以使用C函数atof
,删除所有“”字符后:
#include <string>
#include <algorithm>
#include <stdlib.h>
double strToDouble(string str)
{
str.erase(remove(str.begin(), str.end(), ','), str.end());
return atof(str.c_str());
}
它也可以不使用任何C++ 11功能。
答
请检查了这一点。虽然它很大,但它会为你的目的 -
string str = "1,234,567.00",temp="";
temp.resize(str.size());
double first = 0.0, sec = 0.0;
int i=0;
int tempIndex = 0;
while(i<str.size() && str[i]!='.')
{
if(str[i]!=',')
temp[tempIndex++]=str[i];
i++;
}
if(temp.size()>0)
{
for(int index = 0; index < tempIndex ; index++)
{
first = first*10.0 + (temp[index]-'0');
}
}
if(i<str.size())
{
double k = 1;
i++; // get next number after decimal
while(i<str.size())
{
if(str[i]==',')
{
i++;
continue;
}
sec += (str[i]-'0')/(pow(10.0,k));
i++;
k++;
}
}
double num = first+sec;
if(str[0]=='-')
num = (-1.0*num);
printf("%lf\n",num);
我会用这个,而不是使用STL。
C++ 11的'的std :: get_money'只是调用C++ 98的http://en.cppreference.com/w/cpp/locale/money_get/get – Cubbi