How to convert a floating point to a string in C/C ++

Source: Internet
Author: User

Recently, when writing a program, you need to convert a floating point number to a string, especially when you execute SQL, you can search for sprintf_s from the Internet, but I did not try it successfully.

Later, we found that the following two methods can be used to convert a floating point to a string:

Two functions can be used to convert a floating point number to a string: _ gcvt and _ gcvt_s. The latter is an enhanced version. The two functions need the header file: # include
<Stdlib. h>.

For example:

Char carray1 [20];

Char carray2 [20];

Char carray3 [20];

Double nresult = 1.0/3.0;

_ Gcvt_s (carray1, nresult, 10); // format 1, retain 10 after decimal point

Printf ("nresult = % s \ n", carray1 );

// Format 2. Parameter 2 specifies the size of the string array, with 10 digits after the decimal point

_ Gcvt_s (carray2, 20, nresult, 10 );

Printf ("nresult = % s \ n", carray2 );

_ Gcvt (nresult, 12, carray3); // keep 12 digits after the decimal point

Printf ("nresult = % s \ n", carray3 );

Note: The 2nd parameters of these two functions indicate that the number of digits after the decimal point is retained. Therefore, the _ gcvt ratio _ gcvt_s in the above example outputs two more parameters.

We recommend that you use the second form of _ gcvt_s for better security.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.