The private member functions DoubleToString, CStringToDouble and StripEndingZero are used to convert the content of the member variables m_dValue to m_strValue and vice versa. The beauty of the functions is that they don't convert itself, but delegate the real job to std::istringstream and std::ostringstreamrespectively, though the unit must be considered.
double CHertzEdit::CStringToDouble(CString &str){ double d;
if (((m_bNegativAllowed==FALSE) && (str.FindOneOf("-") != -1)) || (str.CompareNoCase("invalid") == 0)) { d=-1.0; } else { // copy String into the stream int i=str.GetLength(); std::istringstream ist(str.GetBuffer(i)); str.ReleaseBuffer();
double d1; char c[3];
// Split value and unit ist >> d1 >> c; CString strEinheit(c);
// Adjust the value to the unit if (!strEinheit.CompareNoCase("Hz")) { d=d1; } else if (!strEinheit.CompareNoCase("kHz")) { d=d1*1000.0; } else if (!strEinheit.CompareNoCase("MHz")) { d=d1*1000000.0; } } return(d);}
std::string CHertzEdit::DoubleToString(double d){ double d1, d2;
std::ostringstream ost; ost.setf(std::ios_base::fixed, std::ios_base::floatfield);
d2=fabs(d);
if (d < 0.0 && !m_bNegativAllowed) { ost << "Invalid" << std::ends; } else if (d2 < 1000.0) // Hz { d1 = d; ost << std::setprecision(1); ost << d1; StripEndingZero(ost); ost << " Hz" << std::ends; } else if (d2 < 1000000.0) // KHz { d1 = d / 1000.0; ost << std::setprecision(4); ost << d1; StripEndingZero(ost); ost << " KHz" << std::ends; } else if (d2 > 10.0e9) // to huge... { ost << "Invalid" << std::ends; } else // MHz { d1 = d / 1000000.0; ost << std::setprecision(7); ost << d1; StripEndingZero(ost); ost << " MHz" << std::ends; } return(ost.str());
}
void CHertzEdit::StripEndingZero(std::ostringstream &oststr){ std::string strString= oststr.str(); std::string::iterator it = strString.end(); --it;
// last char == '0' ? while ( *(it) == '0' && it != strString.begin()) { // yes // is a '.' in front of it? if ( *(it-1) != '.') { // no => erase '0' strString.erase(it); it = strString.end(); --it; } else { // else => keep '0' (e.g. 1.0) break; } } // no // reinit oststr oststr.seekp(0); oststr << strString;}