如何将float转换为string

     可能有好多人,包括C语言老手都不知道如何将float数据转换为string,我就是这样,今天查了一下MSDN,才知道C提供了_gcvt函数实现这个功能,收获着实不小,为了方便自己查询,也为了那些像我这样的网友能够了解该函数的具体用法,我把MSDN的原文原封不动抄录如下:

_gcvt

Converts a floating-point value to a string, which it stores in a buffer.

char *_gcvt( double value, int digits, char *buffer );

RoutineRequired HeaderCompatibility
_gcvt<stdlib.h>Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIBSingle thread static library, retail version
LIBCMT.LIBMultithread static library, retail version
MSVCRT.LIBImport library for MSVCRT.DLL, retail version

Return Value

_gcvt returns a pointer to the string of digits. There is no error return.

Parameters

value

Value to be converted

digits

Number of significant digits stored

buffer

Storage location for result

Remarks

The _gcvt function converts a floating-point value to a character string (which includes a decimal point and a possible sign byte) and stores the string in buffer. The buffer should be large enough to accommodate the converted value plus a terminating null character, which is appended automatically. If a buffer size of digits + 1 is used, the function overwrites the end of the buffer. This is because the converted string includes a decimal point and can contain sign and exponent information. There is no provision for overflow. _gcvt attempts to produce digits digits in decimal format. If it cannot, it produces digits digits in exponential format. Trailing zeros may be suppressed in the conversion.

Example

/* _GCVT.C: This program converts -3.1415e5
 * to its string representation.
 */

#include <stdlib.h>
#include <stdio.h>

void main( void )
{
   char buffer[50];
   double source = -3.1415e5;
   _gcvt( source, 7, buffer );
   printf( "source: %f  buffer: '%s'/n", source, buffer );
   _gcvt( source, 7, buffer );
   printf( "source: %e  buffer: '%s'/n", source, buffer );
}

Output

source: -314150.000000  buffer: '-314150.'
source: -3.141500e+005  buffer: '-314150.'

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值