开发者

efficient function to convert float/double to string

Right now, the only function that I am aware of is _snprintf_s like the following

double dMyV开发者_开发技巧alue = <some value>;
_snprintf_s(pszMyBuffer, sizeof(pszMyBuffer), 12, "%.10f", dMyValue);


Looks like you are using Visual C++. There are also _fcvt_s, _ecvt_s, and _gcvt_s. A main difference from _snprintf_s is that they do not parse a format string, so they should be a little more efficient. The C runtime libraries functions are generally well-tuned, so you probably can't go wrong with any of them.


If you happen to know the value is limited to a certain range, you might be able to beat the built-in function. For example:

if (v < 0){
  strcat(s, "-"); s++;
  v = -v;
}
double di = floor(v);
double frac = v - di;
int i = (int)di;
int f = (int)floor(frac * 1e10);
strcat(s, itoa(i)); s += strlen(s);
strcat(s, "."); s++;
strcat(s, itoa(f)); s += strlen(s);

but I bet you've got bigger fish to fry somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜