السلام عليكــم ورحمـة الله وبركاتــة ،،
هذا الملف يحتوي على دوال قمت ببرمجتها للتحويل بين النصوص والأرقام أرجو أن يكون مفيدا.
// KConvStrNum.h
// convert between strings and numbers
// Programmed by : Khalil Elamin Abduljawwad
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// strToDouble function converts any valid number as string to double .
double strToDouble(string s)
{
string integer,fraction;
int number1=0,number2=0;
short sign=1;
double number3=0;
int j=0,i=0;
float num=0.1;
while(j<s.length() && s[j]!='.' && s[j]!='e' && s[j]!='E')
integer+=s[j++];
if(j<s.length()-1 && s[j]=='.')
{
j++;
while(j<s.length()&& s[j]!='E'&& s[j]!='e')
fraction+=s[j++];
number2=fraction[0]-48;
for(i=1;i<fraction.length();i++)
number2=number2*10+(fraction-48);
for(i=1;i<=fraction.length()-1;i++)
num*=0.1;
}
if(s[j]=='e' ||s[j]=='E')
{
j++;
int sign=1;
if(s[j]=='+' ||s[j]=='-')
{
if(s[j]=='-')sign=-1;
number3=s[++j]-48;
j++;
}
else
number3=s[j++]-48;
while(j<s.length())
{
number3=number3*10+(s[j++]-48);
}
number3*=sign;
}
if(integer[0]=='+' ||integer[0]=='-')
{
if(integer[0]=='-')sign=-1;
number1=integer[1]-48;
j=2;
}
else
{
j=1;
number1=integer[0]-48;
}
for(;j<integer.length();j++)
number1=number1*10+(s[j]-48);
return (number1+num*number2)*sign*pow(10,number3);
}
//round integr number as string, for example:roundStr("1234567")="124".
string roundStr(string s)
{
for(int i=s.length()-1; i>1; i--)
if(s>='5')
{
s.erase(i,1);
s[i-1]=(s[i-1]-48+1)+48;
}
return s;
}
// convert integer to string:
string intToStr(long i)
{
if(!i)return "0";
bool nega=false;
if(i<0)i*=-1,nega=true;
string n,num;
while(i)
{
n+=(char)(i%10+48);
i/=10;
}
for(int j=n.length()-1;j>=0;j--)
num+=n[j];
if(nega)return "-"+num;
return num;
}
//Convert float or real number to string:
string floatToStr(float f)
{
if(f==0)return "0";
bool nega=false;
if(f<0)nega=true, f*=-1;
long a=f;
long b=(f-a)*100000;
string c=intToStr(b);
if(c.length()>4 && c[c.length()-1]=='1')c.erase(c.length()-1,1);
for(int i=c.length()-1; i>=0;i--)
if(c=='0')c.erase(i,1);
else break;
if(nega)
if(c=="")return "-"+intToStr(a);
else return "-"+intToStr(a)+"."+roundStr(c);
if(c=="")return intToStr(a);
return intToStr(a)+"."+ roundStr(c);
}